Skip to content

Commit c54088d

Browse files
authored
Random cleanup (#7173)
* Use Shouldly * Delete ToolsVersion and xmlns * new() without type * Use $ to format string literals * Clean up exceptions * Inline variable declaration * => for simple methods * Add space * PR comments * Use named functions to clarify meaning of exceptions * Use ContainsKey
1 parent 8132cae commit c54088d

File tree

59 files changed

+272
-763
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

59 files changed

+272
-763
lines changed

src/Build.OM.UnitTests/Definition/Project_Tests.cs

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2109,10 +2109,6 @@ public void BuildEvaluationUsesCustomLoggers()
21092109
{
21102110
result = project.Build(new ILogger[] { mockLogger });
21112111
}
2112-
catch
2113-
{
2114-
throw;
2115-
}
21162112
finally
21172113
{
21182114
project.ProjectCollection.UnregisterAllLoggers();

src/Build.UnitTests/BackEnd/AssemblyTaskFactory_Tests.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
using Microsoft.Build.Construction;
1212
using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
1313
using Xunit;
14+
using Shouldly;
1415

1516
#nullable disable
1617

@@ -257,8 +258,8 @@ public void VerifyGoodTaskInstantiation()
257258
new AppDomainSetup(),
258259
#endif
259260
false);
260-
Assert.NotNull(createdTask);
261-
Assert.False(createdTask is TaskHostTask);
261+
createdTask.ShouldNotBeNull();
262+
createdTask.ShouldNotBeOfType<TaskHostTask>();
262263
}
263264
finally
264265
{

src/Build.UnitTests/BackEnd/BuildManager_Tests.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1681,11 +1681,11 @@ public void CancelledBuildWithDelay40()
16811681
[Fact]
16821682
public void CancelledBuildInTaskHostWithDelay40()
16831683
{
1684-
string contents = CleanupFileContents(@"
1684+
string contents = CleanupFileContents(@$"
16851685
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
16861686
<UsingTask TaskName='Microsoft.Build.Tasks.Exec' AssemblyName='Microsoft.Build.Tasks.Core, Version=msbuildassemblyversion, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' TaskFactory='TaskHostFactory' />
16871687
<Target Name='test'>
1688-
<Exec Command='" + Helpers.GetSleepCommand(TimeSpan.FromSeconds(10)) + @"'/>
1688+
<Exec Command='{Helpers.GetSleepCommand(TimeSpan.FromSeconds(10))}'/>
16891689
<Message Text='[errormessage]'/>
16901690
</Target>
16911691
</Project>

src/Build.UnitTests/BackEnd/TargetBuilder_Tests.cs

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1601,19 +1601,10 @@ private ProjectInstance CreateTestProject(string projectBodyContents, string ini
16011601
File.Create("testProject.proj").Dispose();
16021602
break;
16031603
}
1604-
catch (Exception ex)
1604+
// If all the retries failed, fail with the actual problem instead of some difficult-to-understand issue later.
1605+
catch (Exception ex) when (retries < 4)
16051606
{
1606-
if (retries < 4)
1607-
{
1608-
Console.WriteLine(ex.ToString());
1609-
}
1610-
else
1611-
{
1612-
// All the retries have failed. We will now fail with the
1613-
// actual problem now instead of with some more difficult-to-understand
1614-
// issue later.
1615-
throw;
1616-
}
1607+
Console.WriteLine(ex.ToString());
16171608
}
16181609
}
16191610

src/Build.UnitTests/BackEnd/TaskHostFactory_Tests.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ public void TaskNodesDieAfterBuild()
2929
</Target>
3030
</Project>";
3131
TransientTestFile project = env.CreateFile("testProject.csproj", pidTaskProject);
32-
ProjectInstance projectInstance = new ProjectInstance(project.Path);
32+
ProjectInstance projectInstance = new(project.Path);
3333
projectInstance.Build().ShouldBeTrue();
3434
string processId = projectInstance.GetPropertyValue("PID");
3535
string.IsNullOrEmpty(processId).ShouldBeFalse();

src/Build.UnitTests/EscapingInProjects_Tests.cs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
using Xunit;
2323
using Xunit.Abstractions;
2424
using Microsoft.Build.Shared;
25+
using Shouldly;
2526

2627
#nullable disable
2728

@@ -128,11 +129,11 @@ public void SemicolonInPropertyPassedIntoStringParam_UsingTaskHost()
128129
[Fact]
129130
public void SemicolonInPropertyPassedIntoITaskItemParam()
130131
{
131-
MockLogger logger = Helpers.BuildProjectWithNewOMExpectSuccess(String.Format(@"
132+
MockLogger logger = Helpers.BuildProjectWithNewOMExpectSuccess(@$"
132133
133134
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
134135
135-
<UsingTask TaskName=`Microsoft.Build.UnitTests.EscapingInProjects_Tests.MyTestTask` AssemblyFile=`{0}` />
136+
<UsingTask TaskName=`Microsoft.Build.UnitTests.EscapingInProjects_Tests.MyTestTask` AssemblyFile=`{new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath}` />
136137
137138
<PropertyGroup>
138139
<MyPropertyWithSemicolons>abc %3b def %3b ghi</MyPropertyWithSemicolons>
@@ -144,7 +145,7 @@ public void SemicolonInPropertyPassedIntoITaskItemParam()
144145
145146
</Project>
146147
147-
", new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath),
148+
",
148149
logger: new MockLogger(_output));
149150

150151
logger.AssertLogContains("Received TaskItemParam: 123 abc ; def ; ghi 789");
@@ -717,14 +718,14 @@ public void EscapedWildcardsShouldNotBeExpanded()
717718
[Trait("Category", "mono-osx-failing")]
718719
public void EscapedWildcardsShouldNotBeExpanded_InTaskHost()
719720
{
720-
MockLogger logger = new MockLogger();
721+
MockLogger logger = new();
721722

722723
try
723724
{
724725
// Populate the project directory with three physical files on disk -- a.weirdo, b.weirdo, c.weirdo.
725726
EscapingInProjectsHelper.CreateThreeWeirdoFiles();
726727
Project project = ObjectModelHelpers.CreateInMemoryProject(@"
727-
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
728+
<Project>
728729
<UsingTask TaskName=`Message` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` TaskFactory=`TaskHostFactory` />
729730
730731
<Target Name=`t`>
@@ -736,8 +737,7 @@ public void EscapedWildcardsShouldNotBeExpanded_InTaskHost()
736737
</Project>
737738
");
738739

739-
bool success = project.Build(logger);
740-
Assert.True(success); // "Build failed. See test output (Attachments in Azure Pipelines) for details"
740+
project.Build(logger).ShouldBeTrue("Build failed. See test output (Attachments in Azure Pipelines) for details");
741741
logger.AssertLogContains("[*]");
742742
}
743743
finally

src/Build/BackEnd/BuildManager/BuildManager.cs

Lines changed: 12 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1727,10 +1727,9 @@ void IssueBuildSubmissionToSchedulerImpl(BuildSubmission submission, bool allowM
17271727
HandleNewRequest(Scheduler.VirtualNode, blocker);
17281728
}
17291729
}
1730-
catch (Exception ex) when (!ExceptionHandling.IsCriticalException(ex))
1730+
catch (Exception ex) when (IsInvalidProjectOrIORelatedException(ex))
17311731
{
1732-
var projectException = ex as InvalidProjectFileException;
1733-
if (projectException != null)
1732+
if (ex is InvalidProjectFileException projectException)
17341733
{
17351734
if (!projectException.HasBeenLogged)
17361735
{
@@ -1739,10 +1738,6 @@ void IssueBuildSubmissionToSchedulerImpl(BuildSubmission submission, bool allowM
17391738
projectException.HasBeenLogged = true;
17401739
}
17411740
}
1742-
else if ((ex is BuildAbortedException) || ExceptionHandling.NotExpectedException(ex))
1743-
{
1744-
throw;
1745-
}
17461741

17471742
lock (_syncLock)
17481743
{
@@ -1752,7 +1747,7 @@ void IssueBuildSubmissionToSchedulerImpl(BuildSubmission submission, bool allowM
17521747
_legacyThreadingData.MainThreadSubmissionId = -1;
17531748
}
17541749

1755-
if (projectException == null)
1750+
if (ex is not InvalidProjectFileException)
17561751
{
17571752
var buildEventContext = new BuildEventContext(submission.SubmissionId, 1, BuildEventContext.InvalidProjectInstanceId, BuildEventContext.InvalidProjectContextId, BuildEventContext.InvalidTargetId, BuildEventContext.InvalidTaskId);
17581753
((IBuildComponentHost)this).LoggingService.LogFatalBuildError(buildEventContext, ex, new BuildEventFileInfo(submission.BuildRequestData.ProjectFullPath));
@@ -1772,6 +1767,11 @@ void IssueBuildSubmissionToSchedulerImpl(BuildSubmission submission, bool allowM
17721767
}
17731768
}
17741769

1770+
private bool IsInvalidProjectOrIORelatedException(Exception e)
1771+
{
1772+
return !ExceptionHandling.IsCriticalException(e) && !ExceptionHandling.NotExpectedException(e) && e is not BuildAbortedException;
1773+
}
1774+
17751775
private void ExecuteGraphBuildScheduler(GraphBuildSubmission submission)
17761776
{
17771777
try
@@ -1855,15 +1855,15 @@ private void ExecuteGraphBuildScheduler(GraphBuildSubmission submission)
18551855
submission.SubmissionId,
18561856
new ReadOnlyDictionary<ProjectGraphNode, BuildResult>(resultsPerNode ?? new Dictionary<ProjectGraphNode, BuildResult>())));
18571857
}
1858-
catch (Exception ex) when (!ExceptionHandling.IsCriticalException(ex))
1858+
catch (Exception ex) when (IsInvalidProjectOrIORelatedException(ex))
18591859
{
18601860
GraphBuildResult result = null;
18611861

18621862
// ProjectGraph throws an aggregate exception with InvalidProjectFileException inside when evaluation fails
18631863
if (ex is AggregateException aggregateException && aggregateException.InnerExceptions.All(innerException => innerException is InvalidProjectFileException))
18641864
{
18651865
// Log each InvalidProjectFileException encountered during ProjectGraph creation
1866-
foreach (var innerException in aggregateException.InnerExceptions)
1866+
foreach (Exception innerException in aggregateException.InnerExceptions)
18671867
{
18681868
var projectException = (InvalidProjectFileException) innerException;
18691869
if (!projectException.HasBeenLogged)
@@ -1881,23 +1881,16 @@ private void ExecuteGraphBuildScheduler(GraphBuildSubmission submission)
18811881
BuildEventContext projectBuildEventContext = new BuildEventContext(submission.SubmissionId, 1, BuildEventContext.InvalidProjectInstanceId, BuildEventContext.InvalidProjectContextId, BuildEventContext.InvalidTargetId, BuildEventContext.InvalidTaskId);
18821882
((IBuildComponentHost)this).LoggingService.LogInvalidProjectFileError(projectBuildEventContext, new InvalidProjectFileException(ex.Message, ex));
18831883
}
1884-
else if (ex is BuildAbortedException || ExceptionHandling.NotExpectedException(ex))
1885-
{
1886-
throw;
1887-
}
18881884
else
18891885
{
18901886
// Arbitrarily just choose the first entry point project's path
1891-
var projectFile = submission.BuildRequestData.ProjectGraph?.EntryPointNodes.First().ProjectInstance.FullPath
1887+
string projectFile = submission.BuildRequestData.ProjectGraph?.EntryPointNodes.First().ProjectInstance.FullPath
18921888
?? submission.BuildRequestData.ProjectGraphEntryPoints?.First().ProjectFile;
18931889
BuildEventContext buildEventContext = new BuildEventContext(submission.SubmissionId, 1, BuildEventContext.InvalidProjectInstanceId, BuildEventContext.InvalidProjectContextId, BuildEventContext.InvalidTargetId, BuildEventContext.InvalidTaskId);
18941890
((IBuildComponentHost)this).LoggingService.LogFatalBuildError(buildEventContext, ex, new BuildEventFileInfo(projectFile));
18951891
}
18961892

1897-
if (result == null)
1898-
{
1899-
result = new GraphBuildResult(submission.SubmissionId, ex);
1900-
}
1893+
result ??= new GraphBuildResult(submission.SubmissionId, ex);
19011894

19021895
ReportResultsToSubmission(result);
19031896

src/Build/BackEnd/Components/BuildRequestEngine/BuildRequestEntry.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -232,8 +232,7 @@ public bool ResolveConfigurationRequest(int unresolvedConfigId, int configId)
232232
{
233233
lock (GlobalLock)
234234
{
235-
List<BuildRequest> requests = null;
236-
if (_unresolvedConfigurations?.TryGetValue(unresolvedConfigId, out requests) != true)
235+
if (_unresolvedConfigurations?.TryGetValue(unresolvedConfigId, out List<BuildRequest> requests) != true)
237236
{
238237
return false;
239238
}

src/Build/BackEnd/Components/Caching/ConfigCache.cs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -120,8 +120,7 @@ public BuildRequestConfiguration GetMatchingConfiguration(ConfigurationMetadata
120120
ErrorUtilities.VerifyThrowArgumentNull(configMetadata, nameof(configMetadata));
121121
lock (_lockObject)
122122
{
123-
int configId;
124-
if (!_configurationIdsByMetadata.TryGetValue(configMetadata, out configId))
123+
if (!_configurationIdsByMetadata.TryGetValue(configMetadata, out int configId))
125124
{
126125
return null;
127126
}
@@ -216,10 +215,9 @@ public List<int> ClearNonExplicitlyLoadedConfigurations()
216215
{
217216
foreach (KeyValuePair<ConfigurationMetadata, int> metadata in _configurationIdsByMetadata)
218217
{
219-
BuildRequestConfiguration configuration;
220218
int configId = metadata.Value;
221219

222-
if (_configurations.TryGetValue(configId, out configuration))
220+
if (_configurations.TryGetValue(configId, out BuildRequestConfiguration configuration))
223221
{
224222
// We do not want to retain this configuration
225223
if (!configuration.ExplicitlyLoaded)

src/Build/BackEnd/Components/Caching/ResultsCache.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -224,8 +224,7 @@ public void ClearResultsForConfiguration(int configurationId)
224224
{
225225
lock (_resultsByConfiguration)
226226
{
227-
BuildResult removedResult;
228-
_resultsByConfiguration.TryRemove(configurationId, out removedResult);
227+
_resultsByConfiguration.TryRemove(configurationId, out BuildResult removedResult);
229228

230229
removedResult?.ClearCachedFiles();
231230
}

0 commit comments

Comments
 (0)