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

BuildCheck has better message when Check fails on Initialize #10612

Merged
merged 5 commits into from
Sep 6, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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 src/Build/BackEnd/Components/Logging/EventSourceSink.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using Microsoft.Build.Shared;

using InternalLoggerException = Microsoft.Build.Exceptions.InternalLoggerException;
using System.Diagnostics;
maridematte marked this conversation as resolved.
Show resolved Hide resolved

#nullable disable

Expand Down
31 changes: 31 additions & 0 deletions src/Build/BackEnd/Shared/EventsCreatorHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,35 @@ public static BuildErrorEventArgs CreateErrorEventFromText(BuildEventContext bui

return buildEvent;
}

public static BuildWarningEventArgs CreateWarningEventFromText(BuildEventContext buildEventContext, string? subcategoryResourceName, string? errorCode, string? helpKeyword, BuildEventFileInfo file, string message)
{
ErrorUtilities.VerifyThrowInternalNull(buildEventContext, nameof(buildEventContext));
ErrorUtilities.VerifyThrowInternalNull(file, nameof(file));
ErrorUtilities.VerifyThrowInternalNull(message, nameof(message));

string? subcategory = null;

if (subcategoryResourceName != null)
{
subcategory = AssemblyResources.GetString(subcategoryResourceName);
}

BuildWarningEventArgs buildEvent =
new BuildWarningEventArgs(
subcategory,
errorCode,
file!.File,
file.Line,
file.Column,
file.EndLine,
file.EndColumn,
message,
helpKeyword,
"MSBuild");

buildEvent.BuildEventContext = buildEventContext;

return buildEvent;
}
}
32 changes: 26 additions & 6 deletions src/Build/BuildCheck/Infrastructure/BuildCheckManagerProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ internal void RegisterCustomCheck(
{
if (_enabledDataSources[(int)buildCheckDataSource])
{
List<CheckFactoryContext> checksToRemove = new();
maridematte marked this conversation as resolved.
Show resolved Hide resolved
foreach (var factory in factories)
{
var instance = factory();
Expand All @@ -201,10 +202,24 @@ internal void RegisterCustomCheck(
if (checkFactoryContext != null)
{
_checkRegistry.Add(checkFactoryContext);
SetupSingleCheck(checkFactoryContext, projectPath);
checkContext.DispatchAsComment(MessageImportance.Normal, "CustomCheckSuccessfulAcquisition", instance.FriendlyName);
try
{
SetupSingleCheck(checkFactoryContext, projectPath);
checkContext.DispatchAsComment(MessageImportance.Normal, "CustomCheckSuccessfulAcquisition", instance.FriendlyName);
}
catch (BuildCheckConfigurationException e)
{
checkContext.DispatchAsWarningFromText(
null,
null,
null,
new BuildEventFileInfo(projectPath),
e.Message);
checksToRemove.Add(checkFactoryContext);
}
}
}
RemoveChecks(checksToRemove, checkContext);
}
}
}
Expand Down Expand Up @@ -295,7 +310,7 @@ private void SetupChecksForNewProject(string projectFullPath, ICheckContext chec
}
catch (BuildCheckConfigurationException e)
{
checkContext.DispatchAsErrorFromText(
checkContext.DispatchAsWarningFromText(
null,
null,
null,
Expand All @@ -305,6 +320,14 @@ private void SetupChecksForNewProject(string projectFullPath, ICheckContext chec
}
}

RemoveChecks(checksToRemove, checkContext);

stopwatch.Stop();
_tracingReporter.AddNewProjectStats(stopwatch.Elapsed);
}

private void RemoveChecks(List<CheckFactoryContext> checksToRemove, ICheckContext checkContext)
{
checksToRemove.ForEach(c =>
{
_checkRegistry.Remove(c);
Expand All @@ -316,9 +339,6 @@ private void SetupChecksForNewProject(string projectFullPath, ICheckContext chec
_tracingReporter.AddCheckStats(checkToRemove!.Check.FriendlyName, checkToRemove.Elapsed);
checkToRemove.Check.Dispose();
}

stopwatch.Stop();
_tracingReporter.AddNewProjectStats(stopwatch.Elapsed);
}

public void ProcessEvaluationFinishedEventArgs(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,11 @@ public void DispatchAsErrorFromText(string? subcategoryResourceName, string? err

_eventDispatcher.Dispatch(buildEvent);
}

public void DispatchAsWarningFromText(string? subcategoryResourceName, string? errorCode, string? helpKeyword, BuildEventFileInfo file, string message)
{
BuildWarningEventArgs buildEvent = EventsCreatorHelper.CreateWarningEventFromText(_eventContext, subcategoryResourceName, errorCode, helpKeyword, file, message);

_eventDispatcher.Dispatch(buildEvent);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,8 @@ public void DispatchAsCommentFromText(MessageImportance importance, string messa
public void DispatchAsErrorFromText(string? subcategoryResourceName, string? errorCode, string? helpKeyword, BuildEventFileInfo file, string message)
=> loggingService
.LogErrorFromText(eventContext, subcategoryResourceName, errorCode, helpKeyword, file, message);

public void DispatchAsWarningFromText(string? subcategoryResourceName, string? errorCode, string? helpKeyword, BuildEventFileInfo file, string message)
=> loggingService
.LogWarningFromText(eventContext, subcategoryResourceName, errorCode, helpKeyword, file, message);
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,9 @@ internal interface ICheckContext
/// Dispatch the instance of <see cref="BuildEventContext"/> as a comment with provided text for the message.
/// </summary>
void DispatchAsCommentFromText(MessageImportance importance, string message);

/// <summary>
/// Dispatch the instance of <see cref="BuildEventContext"/> as a warning message.
/// </summary>
void DispatchAsWarningFromText(string? subcategoryResourceName, string? errorCode, string? helpKeyword, BuildEventFileInfo file, string message);
}
31 changes: 31 additions & 0 deletions src/BuildCheck.UnitTests/EndToEndTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,37 @@ public void CustomCheckTest_WithEditorConfig(string checkCandidate, string ruleI
}
}

[Theory]
[InlineData("X01236", "Something went wrong initializing")]
// [InlineData("X01237", "message")]
// [InlineData("X01238", "message")]
public void CustomChecksFailGracefully(string ruleId, string expectedMessage)
{
using (var env = TestEnvironment.Create())
{
string checkCandidate = "CheckCandidateWithMultipleChecksInjected";
string checkCandidatePath = Path.Combine(TestAssetsRootPath, checkCandidate);

// Can't use Transitive environment due to the need to dogfood local nuget packages.
AddCustomDataSourceToNugetConfig(checkCandidatePath);
string editorConfigName = Path.Combine(checkCandidatePath, EditorConfigFileName);
File.WriteAllText(editorConfigName, ReadEditorConfig(
new List<(string, string)>() { (ruleId, "warning") },
ruleToCustomConfig: null,
checkCandidatePath));

string projectCheckBuildLog = RunnerUtilities.ExecBootstrapedMSBuild(
$"{Path.Combine(checkCandidatePath, $"{checkCandidate}.csproj")} /m:1 -nr:False -restore -check -verbosity:n", out bool success);

success.ShouldBeTrue();
projectCheckBuildLog.ShouldContain(expectedMessage);
projectCheckBuildLog.ShouldNotContain("This check should have been disabled");

// Cleanup
File.Delete(editorConfigName);
}
}

[Theory]
[InlineData(true)]
[InlineData(false)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
<ProjectReference Include=".\TestAssets\CustomCheck\CustomCheck.csproj" />
<ProjectReference Include=".\TestAssets\CustomCheck2\CustomCheck2.csproj" />
<ProjectReference Include=".\TestAssets\InvalidCustomCheck\InvalidCustomCheck.csproj" />
<ProjectReference Include=".\TestAssets\ErrorCustomCheck\ErrorCustomCheck.csproj" />
</ItemGroup>

<ItemGroup>
Expand All @@ -45,4 +46,8 @@
</None>
</ItemGroup>

<ItemGroup>
<Compile Remove="TestAssets\ErrorCustomCheck\ErrorWhenRegisteringActions.cs" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,7 @@ root = true

[*.csproj]
build_check.X01234.Severity=X01234Severity

build_check.X01236.Severity=X01236Severity
build_check.X01237.Severity=X01237Severity
build_check.X01238.Severity=X01238Severity
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
<PackageReference Include="CustomCheck" Version="1.0.0"/>
<PackageReference Include="CustomCheck2" Version="1.0.0"/>
<PackageReference Include="InvalidCustomCheck" Version="1.0.0"/>
<PackageReference Include="ErrorCustomCheck" Version="1.0.0"/>
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">

<Import Project="..\Common\CommonTest.props" />

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
</PropertyGroup>

<ItemGroup>
<None Include="ErrorCustomCheck.props" Pack="true" PackagePath="build\ErrorCustomCheck.props" />
<Content Include="README.md" />
</ItemGroup>

<Import Project="..\Common\CommonTest.targets" />

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project>
<PropertyGroup>
<MSBuildCheck>$([MSBuild]::RegisterBuildCheck($(MSBuildThisFileDirectory)ErrorCustomCheck.dll))</MSBuildCheck>
</PropertyGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using System;

Check failure on line 1 in src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnInitializeCheck.cs

View check run for this annotation

Azure Pipelines / msbuild-pr (Linux Core)

src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnInitializeCheck.cs#L1

src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnInitializeCheck.cs(1,1): error IDE0073: (NETCORE_ENGINEERING_TELEMETRY=Build) A source file is missing a required header. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0073)

Check failure on line 1 in src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnInitializeCheck.cs

View check run for this annotation

Azure Pipelines / msbuild-pr (Linux Core)

src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnInitializeCheck.cs#L1

src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnInitializeCheck.cs(1,1): error IDE0073: (NETCORE_ENGINEERING_TELEMETRY=Build) A source file is missing a required header. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0073)

Check failure on line 1 in src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnInitializeCheck.cs

View check run for this annotation

Azure Pipelines / msbuild-pr (macOS Core)

src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnInitializeCheck.cs#L1

src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnInitializeCheck.cs(1,1): error IDE0073: (NETCORE_ENGINEERING_TELEMETRY=Build) A source file is missing a required header. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0073)

Check failure on line 1 in src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnInitializeCheck.cs

View check run for this annotation

Azure Pipelines / msbuild-pr

src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnInitializeCheck.cs#L1

src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnInitializeCheck.cs(1,1): error IDE0073: (NETCORE_ENGINEERING_TELEMETRY=Build) A source file is missing a required header. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0073)

Check failure on line 1 in src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnInitializeCheck.cs

View check run for this annotation

Azure Pipelines / msbuild-pr

src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnInitializeCheck.cs#L1

src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnInitializeCheck.cs(1,1): error IDE0073: (NETCORE_ENGINEERING_TELEMETRY=Build) A source file is missing a required header. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0073)
using System.Collections.Generic;
using Microsoft.Build.Construction;
using Microsoft.Build.Experimental.BuildCheck;

namespace ErrorCustomCheck
{
public sealed class ErrorOnInitializeCheck : Check
{
public static CheckRule SupportedRule = new CheckRule(
"X01236",
"Title",
"Description",
"Message format: {0}",
new CheckConfiguration());

public override string FriendlyName => "ErrorOnInitializeCheck";

public override IReadOnlyList<CheckRule> SupportedRules { get; } = new List<CheckRule>() { SupportedRule };

public override void Initialize(ConfigurationContext configurationContext)
{
// configurationContext to be used only if check needs external configuration data.
throw new Exception("Something went wrong initializing");
}

public override void RegisterActions(IBuildCheckRegistrationContext registrationContext)
{
registrationContext.RegisterEvaluatedPropertiesAction(EvaluatedPropertiesAction);
}

private void EvaluatedPropertiesAction(BuildCheckDataContext<EvaluatedPropertiesCheckData> context)
{
context.ReportResult(BuildCheckResult.Create(
SupportedRule,
ElementLocation.EmptyLocation,
"This check should have been disabled"));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System;

Check failure on line 1 in src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnRegisteredAction.cs

View check run for this annotation

Azure Pipelines / msbuild-pr (Linux Core)

src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnRegisteredAction.cs#L1

src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnRegisteredAction.cs(1,1): error IDE0073: (NETCORE_ENGINEERING_TELEMETRY=Build) A source file is missing a required header. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0073)

Check failure on line 1 in src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnRegisteredAction.cs

View check run for this annotation

Azure Pipelines / msbuild-pr (Linux Core)

src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnRegisteredAction.cs#L1

src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnRegisteredAction.cs(1,1): error IDE0073: (NETCORE_ENGINEERING_TELEMETRY=Build) A source file is missing a required header. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0073)

Check failure on line 1 in src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnRegisteredAction.cs

View check run for this annotation

Azure Pipelines / msbuild-pr (macOS Core)

src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnRegisteredAction.cs#L1

src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnRegisteredAction.cs(1,1): error IDE0073: (NETCORE_ENGINEERING_TELEMETRY=Build) A source file is missing a required header. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0073)

Check failure on line 1 in src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnRegisteredAction.cs

View check run for this annotation

Azure Pipelines / msbuild-pr

src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnRegisteredAction.cs#L1

src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorOnRegisteredAction.cs(1,1): error IDE0073: (NETCORE_ENGINEERING_TELEMETRY=Build) A source file is missing a required header. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0073)
using System.Collections.Generic;
using Microsoft.Build.Construction;
using Microsoft.Build.Experimental.BuildCheck;

namespace ErrorCustomCheck
{
public sealed class ErrorOnRegisteredAction : Check
{
public static CheckRule SupportedRule = new CheckRule(
"X01237",
"Title",
"Description",
"Message format: {0}",
new CheckConfiguration());

public override string FriendlyName => "ErrorOnEvaluatedPropertiesCheck";

public override IReadOnlyList<CheckRule> SupportedRules { get; } = new List<CheckRule>() { SupportedRule };

public override void Initialize(ConfigurationContext configurationContext)
{
// configurationContext to be used only if check needs external configuration data.
}

public override void RegisterActions(IBuildCheckRegistrationContext registrationContext)
{
registrationContext.RegisterEvaluatedPropertiesAction(EvaluatedPropertiesAction);
}

private void EvaluatedPropertiesAction(BuildCheckDataContext<EvaluatedPropertiesCheckData> context)
{
throw new Exception("something went wrong");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using System;

Check failure on line 1 in src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorWhenRegisteringActions.cs

View check run for this annotation

Azure Pipelines / msbuild-pr (Linux Core)

src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorWhenRegisteringActions.cs#L1

src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorWhenRegisteringActions.cs(1,1): error IDE0073: (NETCORE_ENGINEERING_TELEMETRY=Build) A source file is missing a required header. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0073)

Check failure on line 1 in src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorWhenRegisteringActions.cs

View check run for this annotation

Azure Pipelines / msbuild-pr (macOS Core)

src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorWhenRegisteringActions.cs#L1

src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorWhenRegisteringActions.cs(1,1): error IDE0073: (NETCORE_ENGINEERING_TELEMETRY=Build) A source file is missing a required header. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0073)

Check failure on line 1 in src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorWhenRegisteringActions.cs

View check run for this annotation

Azure Pipelines / msbuild-pr

src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorWhenRegisteringActions.cs#L1

src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/ErrorWhenRegisteringActions.cs(1,1): error IDE0073: (NETCORE_ENGINEERING_TELEMETRY=Build) A source file is missing a required header. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0073)
using System.Collections.Generic;
using Microsoft.Build.Construction;
using Microsoft.Build.Experimental.BuildCheck;

namespace ErrorCustomCheck
{
public sealed class ErrorWhenRegisteringActions : Check
{
public static CheckRule SupportedRule = new CheckRule(
"X01238",
"Title",
"Description",
"Message format: {0}",
new CheckConfiguration());

public override string FriendlyName => "ErrorOnEvaluatedPropertiesCheck";

public override IReadOnlyList<CheckRule> SupportedRules { get; } = new List<CheckRule>() { SupportedRule };

public override void Initialize(ConfigurationContext configurationContext)
{
// configurationContext to be used only if check needs external configuration data.
}

public override void RegisterActions(IBuildCheckRegistrationContext registrationContext)
{
registrationContext.RegisterEvaluatedPropertiesAction(EvaluatedPropertiesAction);
throw new Exception("something went wrong");
}

private void EvaluatedPropertiesAction(BuildCheckDataContext<EvaluatedPropertiesCheckData> context)
{
context.ReportResult(BuildCheckResult.Create(
SupportedRule,
ElementLocation.EmptyLocation,
"This check should have been disabled"));
}
}
}
21 changes: 21 additions & 0 deletions src/BuildCheck.UnitTests/TestAssets/ErrorCustomCheck/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# MSBuild Custom Check Template

## Overview
MSBuild Custom Check Template is a .NET template designed to streamline the creation of MSBuild check libraries. This template facilitates the development of custom checks targeting .NET Standard, enabling developers to inspect and enforce conventions, standards, or patterns within their MSBuild builds.

## Features
- Simplified template for creating MSBuild check libraries.
- Targeting .NET Standard for cross-platform compatibility.
- Provides a starting point for implementing custom check rules.

## Getting Started
To use the MSBuild Custom Check Template, follow these steps:
1. Install the template using the following command:
```bash
dotnet new install msbuildcheck
2. Instantiate a custom template:
```bash
dotnet new msbuildcheck -n <ProjectName>

### Prerequisites
- .NET SDK installed on your machine.
Loading