Skip to content

Commit

Permalink
Merge branch 'main' into minor-improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
Corniel authored Nov 1, 2024
2 parents 864cb19 + 5c55d2c commit 199d09c
Show file tree
Hide file tree
Showing 18 changed files with 404 additions and 77 deletions.
1 change: 0 additions & 1 deletion Buildalyzer.sln
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34622.214
Expand Down
2 changes: 1 addition & 1 deletion azure-pipelines.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ trigger:
- '*'
branches:
include:
- main
- release/*

pool:
vmImage: 'ubuntu-latest'
Expand Down
4 changes: 2 additions & 2 deletions src/Buildalyzer.Workspaces/Buildalyzer.Workspaces.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ ToBeReleased
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.4.0" />
<PackageReference Include="Microsoft.CodeAnalysis.VisualBasic.Workspaces" Version="4.4.0" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.10.0" />
<PackageReference Include="Microsoft.CodeAnalysis.VisualBasic.Workspaces" Version="4.10.0" />
</ItemGroup>

<ItemGroup>
Expand Down
6 changes: 3 additions & 3 deletions src/Buildalyzer/Buildalyzer.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ ToBeReleased
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Build" Version="17.0.1" />
<PackageReference Include="Microsoft.Build.Tasks.Core" Version="17.0.1" />
<PackageReference Include="Microsoft.Build" Version="17.10.4" />
<PackageReference Include="Microsoft.Build.Tasks.Core" Version="17.10.4" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="[4,)" />
<PackageReference Include="Microsoft.CodeAnalysis.VisualBasic" Version="[4,)" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" />
<PackageReference Include="MSBuild.StructuredLogger" Version="2.1.815" Aliases="StructuredLogger" />
<PackageReference Include="MSBuild.StructuredLogger" Version="2.2.158" Aliases="StructuredLogger" />
<PackageReference Include="MsBuildPipeLogger.Server" Version="1.1.6" />
<PackageReference Include="NuGet.Frameworks" Version="6.9.1" />
</ItemGroup>
Expand Down
47 changes: 26 additions & 21 deletions src/Buildalyzer/Logging/EventProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -145,31 +145,36 @@ private void TargetFinished(object sender, TargetFinishedEventArgs e)

private void MessageRaised(object sender, BuildMessageEventArgs e)
{
AnalyzerResult result = _currentResult.Count == 0 ? null : _currentResult.Peek();
if (result is object)
var result = _currentResult.Count == 0 ? null : _currentResult.Peek();
if (result is not object || !IsRelevant())
{
// Process the command line arguments for the Fsc task
if (e.SenderName?.Equals("Fsc", StringComparison.OrdinalIgnoreCase) == true
&& !string.IsNullOrWhiteSpace(e.Message)
&& _targetStack.Any(x => x.TargetName == "CoreCompile")
&& result.CompilerCommand is null)
{
result.ProcessFscCommandLine(e.Message);
}
return;
}

// Process the command line arguments for the Csc task
if (e is TaskCommandLineEventArgs cmd
&& string.Equals(cmd.TaskName, "Csc", StringComparison.OrdinalIgnoreCase))
{
result.ProcessCscCommandLine(cmd.CommandLine, _targetStack.Any(x => x.TargetName == "CoreCompile"));
}
// Process the command line arguments for the Fsc task
if (e.SenderName?.Equals("Fsc", StringComparison.OrdinalIgnoreCase) == true
&& !string.IsNullOrWhiteSpace(e.Message)
&& _targetStack.Any(x => x.TargetName == "CoreCompile")
&& result.CompilerCommand is null)
{
result.ProcessFscCommandLine(e.Message);
}

if (e is TaskCommandLineEventArgs cmdVbc &&
string.Equals(cmdVbc.TaskName, "Vbc", StringComparison.OrdinalIgnoreCase))
{
result.ProcessVbcCommandLine(cmdVbc.CommandLine);
}
// Process the command line arguments for the Csc task
if (e is TaskCommandLineEventArgs cmd
&& string.Equals(cmd.TaskName, "Csc", StringComparison.OrdinalIgnoreCase))
{
result.ProcessCscCommandLine(cmd.CommandLine, _targetStack.Any(x => x.TargetName == "CoreCompile"));
}

if (e is TaskCommandLineEventArgs cmdVbc &&
string.Equals(cmdVbc.TaskName, "Vbc", StringComparison.OrdinalIgnoreCase))
{
result.ProcessVbcCommandLine(cmdVbc.CommandLine);
}

bool IsRelevant() => string.IsNullOrEmpty(result.Command) || AnalyzerManager.NormalizePath(e.ProjectFile) == _projectFilePath;

}

private void BuildFinished(object sender, BuildFinishedEventArgs e)
Expand Down
74 changes: 39 additions & 35 deletions tests/Buildalyzer.Tests/Integration/SimpleProjectsFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.IO;
using System.IO.Compression;
using Buildalyzer.Environment;
using Buildalyzer.TestTools;
using FluentAssertions;
using Shouldly;

Expand Down Expand Up @@ -39,6 +40,7 @@ public class SimpleProjectsFixture
@"SdkNet6SelfContained\SdkNet6SelfContained.csproj",
@"SdkNet6ImplicitUsings\SdkNet6ImplicitUsings.csproj",
@"SdkNet7Project\SdkNet7Project.csproj",
@"SdkNet8CS12FeaturesProject\SdkNet8CS12FeaturesProject.csproj",
@"SdkNetCore2ProjectImport\SdkNetCore2ProjectImport.csproj",
@"SdkNetCore2ProjectWithReference\SdkNetCore2ProjectWithReference.csproj",
@"SdkNetCore2ProjectWithImportedProps\SdkNetCore2ProjectWithImportedProps.csproj",
Expand All @@ -59,27 +61,23 @@ public class SimpleProjectsFixture
};

[Test]
public void DesignTimeBuildsProject(
public void Builds_DesignTime(
[ValueSource(nameof(Preferences))] EnvironmentPreference preference,
[ValueSource(nameof(ProjectFiles))] string projectFile)
{
// Given
StringWriter log = new StringWriter();
IProjectAnalyzer analyzer = GetProjectAnalyzer(projectFile, log);
EnvironmentOptions options = new EnvironmentOptions
using var ctx = Context.ForProject(projectFile);

var options = new EnvironmentOptions
{
Preference = preference
Preference = preference,
DesignTime = true,
};

// When
DeleteProjectDirectory(projectFile, "obj");
DeleteProjectDirectory(projectFile, "bin");
IAnalyzerResults results = analyzer.Build(options);
var results = ctx.Analyzer.Build(options);

// Then
results.Count.ShouldBeGreaterThan(0, log.ToString());
results.OverallSuccess.ShouldBeTrue(log.ToString());
results.ShouldAllBe(x => x.Succeeded, log.ToString());
results.Should().NotBeEmpty();
results.OverallSuccess.Should().BeTrue();
results.Should().AllSatisfy(r => r.Succeeded.Should().BeTrue());
}

[Test]
Expand Down Expand Up @@ -138,7 +136,7 @@ public void GetsSourceFiles(
[Test]
public void GetsReferences(
[ValueSource(nameof(Preferences))] EnvironmentPreference preference,
[ValueSource(nameof(ProjectFiles))] [NotNull] string projectFile)
[ValueSource(nameof(ProjectFiles))][NotNull] string projectFile)
{
// Given
StringWriter log = new StringWriter();
Expand Down Expand Up @@ -226,6 +224,29 @@ public void WpfControlLibraryGetsSourceFiles()
}.ShouldBeSubsetOf(sourceFiles.Select(x => Path.GetFileName(x)), log.ToString());
}

[Test]
[Platform("win")]
public void AzureFunctionSourceFiles()
{
// Given
StringWriter log = new StringWriter();
IProjectAnalyzer analyzer = GetProjectAnalyzer(@"AzureFunctionProject\AzureFunctionProject.csproj", log);

// When
IAnalyzerResults results = analyzer.Build();

// Then
IReadOnlyList<string> sourceFiles = results.SingleOrDefault()?.SourceFiles;
sourceFiles.ShouldNotBeNull(log.ToString());
new[]
{
"Program",
"TestFunction",
"AssemblyAttributes",
"AssemblyInfo"
}.ShouldBeSubsetOf(sourceFiles.Select(x => Path.GetFileName(x).Split('.').TakeLast(2).First()), log.ToString());
}

[Test]
public void MultiTargetingBuildAllTargetFrameworksGetsSourceFiles()
{
Expand Down Expand Up @@ -684,7 +705,7 @@ public static void DuplicateProjectReferences()
}

[Test]
public void GetsAdditionalCscFiles()
public void Resolves_additional_files_for_Razor_project()
{
// Given
StringWriter log = new StringWriter();
Expand All @@ -698,7 +719,7 @@ public void GetsAdditionalCscFiles()
}

[Test]
public void GetsAdditionalFile()
public void Resolves_additional_files()
{
// Given
StringWriter log = new StringWriter();
Expand All @@ -709,24 +730,7 @@ public void GetsAdditionalFile()
.Should().BeEquivalentTo("message.txt");
}

[Test]
public void HandlesProcessFailure()
{
// Given
StringWriter log = new StringWriter();
IProjectAnalyzer analyzer = GetProjectAnalyzer(@"SdkNet6Exe\SdkNet6Exe.csproj", log);

// When
IAnalyzerResults results = analyzer.Build(new EnvironmentOptions
{
Arguments = { "/unknown" } // This argument will cause msbuild to immediately fail
});

// Then
results.OverallSuccess.ShouldBeFalse();
}

private static IProjectAnalyzer GetProjectAnalyzer(string projectFile, StringWriter log)
private static IProjectAnalyzer GetProjectAnalyzer(string projectFile, System.IO.StringWriter log)
{
IProjectAnalyzer analyzer = new AnalyzerManager(
new AnalyzerManagerOptions
Expand Down
90 changes: 90 additions & 0 deletions tests/Buildalyzer.Tests/TestTools/BuildalyzerTestContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
using System.Diagnostics;
using System.IO;

namespace Buildalyzer.TestTools;

/// <summary>Creates a test context for testing <see cref="IProjectAnalyzer"/>s.</summary>
/// <remarks>
/// The context ensures an fresh build (deletes previous artifacts in advance).
/// The context logs to the console in DEBUG mode.
/// </remarks>
public sealed class BuildalyzerTestContext : IDisposable
{
public TextWriter Log => IsDisposed ? throw new ObjectDisposedException(GetType().FullName) : log;

[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly TextWriter log = new StringWriter();

public BuildalyzerTestContext(FileInfo projectFile)
{
ProjectFile = projectFile;
Manager = new AnalyzerManager(
new AnalyzerManagerOptions
{
LogWriter = Log,
});

Analyzer = Manager.GetProject(projectFile.FullName);

DebugMode(ref InDebugMode);
AddBinaryLogger();
DeleteSubDirectory("bin");
DeleteSubDirectory("obj");
}

public FileInfo ProjectFile { get; }

public AnalyzerManager Manager { get; }

public IProjectAnalyzer Analyzer { get; }

/// <inheritdoc />
public void Dispose()
{
if (!IsDisposed)
{
if (InDebugMode)
{
Console.WriteLine(Log.ToString());
}
Log.Dispose();

IsDisposed = true;
}
}

[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private bool IsDisposed;

/// <summary>Ensures that the analysis is done ignoring previous results.</summary>
private void DeleteSubDirectory(string path)
{
var directory = new DirectoryInfo(Path.Combine(ProjectFile.Directory!.FullName, path));

if (directory.Exists)
{
try
{
directory.Delete(true);
Log.WriteLine($"Deleted all files at {directory}");
}
catch (Exception x)
{
Log.WriteLine(x);
}
}
}

[Conditional("BinaryLog")]
private void AddBinaryLogger()
{
Analyzer.AddBinaryLogger(Path.Combine(@"C:\Temp\", Path.ChangeExtension(ProjectFile.Name, ".core.binlog")));
}

/// <summary>Sets <paramref name="inDebugMode"/> to true when run in DEBUG mode.</summary>
[Conditional("DEBUG")]
private void DebugMode(ref bool inDebugMode) => inDebugMode = true;

[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly bool InDebugMode;
}
23 changes: 23 additions & 0 deletions tests/Buildalyzer.Tests/TestTools/Context.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System.Diagnostics.Contracts;
using System.IO;

namespace Buildalyzer.TestTools;

public static class Context
{
[Pure]
public static BuildalyzerTestContext ForProject(string path) => new(GetProjectPath(path));

private static FileInfo GetProjectPath(string file)
{
var location = new FileInfo(typeof(Context).Assembly.Location).Directory!;
return new FileInfo(Path.Combine(
location.FullName,
"..",
"..",
"..",
"..",
"projects",
file));
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
Expand Down Expand Up @@ -27,6 +27,7 @@

<ItemGroup>
<ProjectReference Include="../../src/Buildalyzer.Workspaces/Buildalyzer.Workspaces.csproj" />
<ProjectReference Include="../Buildalyzer.Tests/Buildalyzer.Tests.csproj" />
</ItemGroup>

<ItemGroup Label="Additional files">
Expand Down
Loading

0 comments on commit 199d09c

Please sign in to comment.