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
2 changes: 1 addition & 1 deletion documentation/specs/BuildCheck/Codes.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ Report codes are chosen to conform to suggested guidelines. Those guidelines are
| [BC0201](#bc0201---usage-of-undefined-property) | Warning | Project | 9.0.100 | Usage of undefined property. |
| [BC0202](#bc0202---property-first-declared-after-it-was-used) | Warning | Project | 9.0.100 | Property first declared after it was used. |
| [BC0203](#bc0203----property-declared-but-never-used) | None | Project | 9.0.100 | Property declared but never used. |
| [BC0301](#bc0301---building-from-downloads-folder) | None | Project | 9.0.300 | Building from Downloads folder. |
| [BC0301](#bc0301---building-from-downloads-folder) | Error | Project | 9.0.300 | Building from Downloads folder. |
Comment thread
AR-May marked this conversation as resolved.
Resolved
| [BC0302](#bc0302---building-using-the-exec-task) | Warning | N/A | 9.0.300 | Building using the Exec task. |

Notes:
Expand Down
22 changes: 17 additions & 5 deletions src/Build/BuildCheck/Checks/DoubleWritesCheck.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Frozen;
using System.Collections.Generic;
#if !FEATURE_MSIOREDIST
using System.IO;
#endif
using System.Linq;
using Microsoft.Build.Collections;
using Microsoft.Build.Shared;
using static Microsoft.Build.Experimental.BuildCheck.TaskInvocationCheckData;

Expand Down Expand Up @@ -46,15 +48,25 @@ public override void RegisterActions(IBuildCheckRegistrationContext registration
/// </summary>
private readonly Dictionary<string, (string projectFilePath, string taskName)> _filesWritten = new(StringComparer.CurrentCultureIgnoreCase);

/// <summary>
/// Compiler tasks known to write files.
/// </summary>
private static readonly FrozenSet<string> s_compilerTaskNames = new[] { "Csc", "Vbc", "Fsc" }.ToFrozenSet(MSBuildNameIgnoreCaseComparer.Default);

private void TaskInvocationAction(BuildCheckDataContext<TaskInvocationCheckData> context)
{
// This check uses a hard-coded list of tasks known to write files.
switch (context.Data.TaskName)
// Task names are matched case-insensitively - MSBuild resolves task names without regard to casing,
// so the logged name carries whatever casing the project author used.
string taskName = context.Data.TaskName;

if (s_compilerTaskNames.Contains(taskName))
{
CheckCompilerTask(context);
}
else if (MSBuildNameIgnoreCaseComparer.Default.Equals(taskName, "Copy"))
{
case "Csc":
case "Vbc":
case "Fsc": CheckCompilerTask(context); break;
case "Copy": CheckCopyTask(context); break;
CheckCopyTask(context);
}
}

Expand Down
5 changes: 4 additions & 1 deletion src/Build/BuildCheck/Checks/ExecCliBuildCheck.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#if !FEATURE_MSIOREDIST
using System.IO;
#endif
using Microsoft.Build.Collections;
using Microsoft.Build.Shared;

#if FEATURE_MSIOREDIST
Expand Down Expand Up @@ -61,7 +62,9 @@ public override void RegisterActions(IBuildCheckRegistrationContext registration

private static void TaskInvocationAction(BuildCheckDataContext<TaskInvocationCheckData> context)
{
if (context.Data.TaskName == ExecTaskName
// Task names are matched case-insensitively - MSBuild resolves task names without regard to casing,
// so the logged name carries whatever casing the project author used.
if (MSBuildNameIgnoreCaseComparer.Default.Equals(context.Data.TaskName, ExecTaskName)
&& context.Data.Parameters.TryGetValue(CommandParameterName, out TaskInvocationCheckData.TaskParameter? commandArgument))
{
var execCommandValue = commandArgument.Value?.ToString() ?? string.Empty;
Expand Down
2 changes: 1 addition & 1 deletion src/Build/BuildCheck/Checks/PropertiesUsageCheck.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public override void Initialize(ConfigurationContext configurationContext)
_unusedPropertyEnabled = config.IsEnabled;
_unusedPropertyScope = config.EvaluationCheckScope;

config = configurationContext.CheckConfig.FirstOrDefault(c => c.RuleId == _usedBeforeInitializedRule.Id)
config = configurationContext.CheckConfig.FirstOrDefault(c => c.RuleId == _initializedAfterUsedRule.Id)
?? CheckConfigurationEffective.Default;

_initializedAfterUseEnabled = config.IsEnabled;
Expand Down
5 changes: 4 additions & 1 deletion src/Build/BuildCheck/Infrastructure/BuildEventsProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Build.Collections;
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Framework;
Expand Down Expand Up @@ -149,7 +150,9 @@ internal void ProcessTaskStartedEventArgs(

// Add a new entry to _tasksBeingExecuted. TaskParameters are initialized empty and will be recorded
// based on TaskParameterEventArgs we receive later.
Dictionary<string, TaskInvocationCheckData.TaskParameter> taskParameters = new();
// Parameter names are MSBuild names - compare them case-insensitively so checks are not sensitive
// to the casing a project author happened to use.
Dictionary<string, TaskInvocationCheckData.TaskParameter> taskParameters = new(MSBuildNameIgnoreCaseComparer.Default);

ExecutingTaskData taskData = new()
{
Expand Down
23 changes: 23 additions & 0 deletions src/BuildCheck.UnitTests/DoubleWritesAnalyzer_Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,33 @@ public void TestCopyTask()
_registrationContext.Results[0].CheckRule.Id.ShouldBe("BC0102");
}

[Theory]
[InlineData("Copy")]
[InlineData("copy")]
[InlineData("COPY")]
public void TestCopyTask_TaskNameCasingIsIgnored(string taskName)
{
_registrationContext.TriggerTaskInvocationAction(MakeTaskInvocationData(taskName, new Dictionary<string, TaskInvocationCheckData.TaskParameter>
{
{ "SourceFiles", new TaskInvocationCheckData.TaskParameter("source1", IsOutput: false) },
{ "DestinationFolder", new TaskInvocationCheckData.TaskParameter("outdir", IsOutput: false) },
}));
_registrationContext.TriggerTaskInvocationAction(MakeTaskInvocationData(taskName, new Dictionary<string, TaskInvocationCheckData.TaskParameter>
{
{ "SourceFiles", new TaskInvocationCheckData.TaskParameter("source1", IsOutput: false) },
{ "DestinationFiles", new TaskInvocationCheckData.TaskParameter(Path.Combine("outdir", "source1"), IsOutput: false) },
}));

_registrationContext.Results.Count.ShouldBe(1);
_registrationContext.Results[0].CheckRule.Id.ShouldBe("BC0102");
}

[Theory]
[InlineData("Csc")]
[InlineData("Vbc")]
[InlineData("Fsc")]
[InlineData("csc")]
[InlineData("VBC")]
public void TestCompilerTask(string taskName)
{
for (int i = 0; i < 2; i++)
Expand Down
25 changes: 25 additions & 0 deletions src/BuildCheck.UnitTests/EndToEndTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,31 @@ public void PropertiesUsageAnalyzerTest(bool buildInOutOfProcessNode)
Regex.Matches(output, "BC0203 .* Property").Count.ShouldBe(2);
}

[Fact]
public void PropertiesUsageCheck_RulesAreIndependentlyConfigurable()
{
PrepareSampleProjectsAndConfig(
buildInOutOfProcessNode: false,
out TransientTestFile projectFile,
out TransientTestFile editorconfigFile,
"PropsCheckTest.csproj");

// Turning BC0201 off must not turn BC0202 off - they are separately configurable rules
// that happen to be implemented by a single check.
File.WriteAllText(
editorconfigFile.Path,
File.ReadAllText(editorconfigFile.Path)
.Replace("build_check.BC0201.Severity=warning", "build_check.BC0201.Severity=none"));

string output = RunnerUtilities.ExecBootstrapedMSBuild($"{projectFile.Path} -check", out bool success, timeoutMilliseconds: timeoutInMilliseconds);
_env.Output.WriteLine(output);
_env.Output.WriteLine("=========================");
success.ShouldBeTrue(output);

output.ShouldNotContain("BC0201");
output.ShouldMatch(@"BC0202: .* Property: 'MyPropT2'");
}

[Theory]
// The culture is not set explicitly, but the extension is a known culture
// - a buildcheck warning will occur, but otherwise works
Expand Down
26 changes: 26 additions & 0 deletions src/BuildCheck.UnitTests/ExecCliBuildCheck_Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,32 @@ public void ExecTask_WithCommandNotExecutingBuild_ShouldNotShowWarning(string? c
_registrationContext.Results.Count.ShouldBe(0);
}

[Theory]
[InlineData("Exec")]
[InlineData("exec")]
[InlineData("EXEC")]
public void ExecTask_WithDifferingTaskNameCasing_ShouldShowWarning(string taskName)
{
_registrationContext.TriggerTaskInvocationAction(MakeTaskInvocationData(taskName, new Dictionary<string, TaskInvocationCheckData.TaskParameter>
{
{ "Command", new TaskInvocationCheckData.TaskParameter("dotnet build", IsOutput: false) },
}));

_registrationContext.Results.Count.ShouldBe(1);
_registrationContext.Results[0].CheckRule.Id.ShouldBe("BC0302");
}

[Fact]
public void DifferentTask_WithBuildCommand_ShouldNotShowWarning()
{
_registrationContext.TriggerTaskInvocationAction(MakeTaskInvocationData("Message", new Dictionary<string, TaskInvocationCheckData.TaskParameter>
{
{ "Command", new TaskInvocationCheckData.TaskParameter("dotnet build", IsOutput: false) },
}));

_registrationContext.Results.Count.ShouldBe(0);
}

private TaskInvocationCheckData MakeTaskInvocationData(string taskName, Dictionary<string, TaskInvocationCheckData.TaskParameter> parameters)
{
string projectFile = Framework.NativeMethods.IsWindows ? @"C:\fake\project.proj" : "/fake/project.proj";
Expand Down
20 changes: 20 additions & 0 deletions src/BuildCheck.UnitTests/TaskInvocationAnalysisDataTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,26 @@ public void ReportsSimpleTaskParameters()
data.Parameters["Text"].Value.ShouldBe("Hello");
}

[Theory]
[InlineData("Text")]
[InlineData("text")]
[InlineData("TEXT")]
[InlineData("tExT")]
public void ReportsTaskParametersKeyedCaseInsensitively(string parameterName)
{
BuildProject("<Message Text='Hello'/>");

s_testCheck!.CheckData.Count.ShouldBe(1);
var data = s_testCheck.CheckData[0];

// Parameter names are MSBuild names, so a check must be able to look them up without
// knowing the casing the task author declared the property with.
data.Parameters.ContainsKey(parameterName).ShouldBeTrue();
data.Parameters.TryGetValue(parameterName, out var parameter).ShouldBeTrue();
parameter.ShouldNotBeNull().Value.ShouldBe("Hello");
data.Parameters[parameterName].Value.ShouldBe("Hello");
}

[Theory]
[InlineData("<Output TaskParameter='CombinedPaths' ItemName='OutputDirectories' />")]
[InlineData("<Output TaskParameter='CombinedPaths' PropertyName='OutputDirectories' />")]
Expand Down