Skip to content

Commit

Permalink
Update to .NET 8 (#412)
Browse files Browse the repository at this point in the history
- Update to .NET 8.
- Use `UseArtifactsOutput=true` instead of explicitly setting the output path, as well as dropping explicit use of `--configuration` now that the default is `Release`.
- Remove Microsoft.SourceLink.GitHub as it is now included in the .NET SDK.
- Use primary constructors where relevant.
- Use collection literals where relevant.
- Apply some IDE suggestions.
- Remove redundant suppressions.
- Remove `CommonAssemblyInfo`.
- Use the new MSBuild terminal logger.
  • Loading branch information
martincostello authored Nov 14, 2023
1 parent 6c38d8e commit 53f94ee
Show file tree
Hide file tree
Showing 24 changed files with 68 additions and 164 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ jobs:
- uses: codecov/codecov-action@eaaf4bedf32dbdc6b720b63067d99c4d77d6047d # v3.1.4
name: Upload coverage to Codecov
with:
file: ./artifacts/coverage/coverage.net7.0.cobertura.xml
file: ./artifacts/coverage/coverage.net8.0.cobertura.xml
flags: ${{ matrix.os_name }}

- name: Publish artifacts
Expand All @@ -70,7 +70,7 @@ jobs:
uses: actions/upload-artifact@a8a3f3ad30e3422c9c7b888a15615d19a852ae32 # v3.1.3
with:
name: packages-${{ matrix.os_name }}
path: ./artifacts/packages
path: ./artifacts/package/release
if-no-files-found: error

validate-packages:
Expand Down
2 changes: 1 addition & 1 deletion .vsconfig
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"components": [
"Microsoft.VisualStudio.Component.CoreEditor",
"Microsoft.VisualStudio.Workload.CoreEditor",
"Microsoft.NetCore.Component.Runtime.7.0",
"Microsoft.NetCore.Component.Runtime.8.0",
"Microsoft.NetCore.Component.SDK",
"Microsoft.VisualStudio.Component.Roslyn.Compiler",
"Microsoft.VisualStudio.Component.Roslyn.LanguageServices"
Expand Down
9 changes: 9 additions & 0 deletions Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
<Project>
<ItemGroup>
<AdditionalFiles Include="$(MSBuildThisFileDirectory)stylecop.json" Link="stylecop.json" />
<AssemblyAttribute Include="System.CLSCompliant">
<_Parameter1>false</_Parameter1>
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
</AssemblyAttribute>
</ItemGroup>
<PropertyGroup>
<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
Expand All @@ -21,6 +25,10 @@
<LangVersion>latest</LangVersion>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
<NeutralLanguage>en-US</NeutralLanguage>
<!--
HACK Workaround for https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3687
-->
<NoWarn>$(NoWarn);SA1010</NoWarn>
<NoWarn>$(NoWarn);CA1848</NoWarn>
<NoWarn Condition=" '$(GenerateDocumentationFile)' != 'true' ">$(NoWarn);SA0001</NoWarn>
<Nullable>enable</Nullable>
Expand All @@ -39,6 +47,7 @@
<StrongNamePublicKey Condition=" '$(SignAssembly)' == 'true'">00240000048000009400000006020000002400005253413100040000010001004b0b2efbada897147aa03d2076278890aefe2f8023562336d206ec8a719b06e89461c31b43abec615918d509158629f93385930c030494509e418bf396d69ce7dbe0b5b2db1a81543ab42777cb98210677fed69dbeb3237492a7ad69e87a1911ed20eb2d7c300238dc6f6403e3d04a1351c5cb369de4e022b18fbec70f7d21ed</StrongNamePublicKey>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<UseArtifactsOutput>true</UseArtifactsOutput>
<AssemblyVersion>0.3.0.0</AssemblyVersion>
<VersionPrefix>0.3.1</VersionPrefix>
<VersionSuffix Condition=" '$(VersionSuffix)' == '' AND '$(GITHUB_ACTIONS)' != '' ">beta$([System.Convert]::ToInt32(`$(GITHUB_RUN_NUMBER)`).ToString(`0000`))</VersionSuffix>
Expand Down
4 changes: 2 additions & 2 deletions Directory.Build.targets
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@
</ItemGroup>
</Target>
<PropertyGroup Condition=" '$(CollectCoverage)' == 'true' ">
<CoverletOutput>$([System.IO.Path]::Combine($(OutputPath), 'coverage', 'coverage'))</CoverletOutput>
<CoverletOutput>$([System.IO.Path]::Combine($(ArtifactsPath), 'coverage', 'coverage'))</CoverletOutput>
<ReportGeneratorOutputMarkdown Condition=" '$(ReportGeneratorOutputMarkdown)' == '' AND '$(GITHUB_SHA)' != '' ">true</ReportGeneratorOutputMarkdown>
<ReportGeneratorReportTypes>HTML</ReportGeneratorReportTypes>
<ReportGeneratorReportTypes Condition=" '$(ReportGeneratorOutputMarkdown)' == 'true' ">$(ReportGeneratorReportTypes);MarkdownSummaryGitHub</ReportGeneratorReportTypes>
<ReportGeneratorTargetDirectory>$([System.IO.Path]::Combine($(OutputPath), 'coverage'))</ReportGeneratorTargetDirectory>
<ReportGeneratorTargetDirectory>$([System.IO.Path]::Combine($(ArtifactsPath), 'coverage'))</ReportGeneratorTargetDirectory>
<_MarkdownSummaryPrefix>&lt;details&gt;&lt;summary&gt;:chart_with_upwards_trend: &lt;b&gt;$(AssemblyName) Code Coverage report&lt;/b&gt;&lt;/summary&gt;</_MarkdownSummaryPrefix>
<_MarkdownSummarySuffix>&lt;/details&gt;</_MarkdownSummarySuffix>
</PropertyGroup>
Expand Down
4 changes: 1 addition & 3 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@
<ItemGroup>
<PackageVersion Include="coverlet.msbuild" Version="6.0.0" />
<PackageVersion Include="GitHubActionsTestLogger" Version="2.3.3" />
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="7.0.13" />
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageVersion Include="Microsoft.SourceLink.GitHub" Version="1.1.1" />
<PackageVersion Include="NSubstitute" Version="5.1.0" />
<PackageVersion Include="ReportGenerator" Version="5.1.26" />
<PackageVersion Include="Shouldly" Version="4.2.1" />
Expand All @@ -21,7 +20,6 @@
<PackageVersion Include="xunit.runner.visualstudio" Version="2.5.3" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" PrivateAssets="All" />
<PackageReference Include="StyleCop.Analyzers" PrivateAssets="All" />
</ItemGroup>
<ItemGroup Condition=" '$(IsTestProject)' == 'true' ">
Expand Down
1 change: 0 additions & 1 deletion Logging.XUnit.sln
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
.gitignore = .gitignore
build.ps1 = build.ps1
CODE_OF_CONDUCT.md = CODE_OF_CONDUCT.md
CommonAssemblyInfo.cs = CommonAssemblyInfo.cs
Directory.Build.props = Directory.Build.props
Directory.Build.targets = Directory.Build.targets
Directory.Packages.props = Directory.Packages.props
Expand Down
34 changes: 9 additions & 25 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,34 +23,25 @@ dotnet add package MartinCostello.Logging.XUnit
### Usage

```csharp
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Xunit;
using Xunit.Abstractions;

namespace MyApp.Calculator;

public class CalculatorTests
public class CalculatorTests(ITestOutputHelper outputHelper)
{
public CalculatorTests(ITestOutputHelper outputHelper)
{
OutputHelper = outputHelper;
}

private ITestOutputHelper OutputHelper { get; }

[Fact]
public void Calculator_Sums_Two_Integers()
{
// Arrange
var services = new ServiceCollection()
.AddLogging((builder) => builder.AddXUnit(OutputHelper))
.AddSingleton<Calculator>();
using var serviceProvider = new ServiceCollection()
.AddLogging((builder) => builder.AddXUnit(outputHelper))
.AddSingleton<Calculator>()
.BuildServiceProvider();

var calculator = services
.BuildServiceProvider()
.GetRequiredService<Calculator>();
var calculator = services.GetRequiredService<Calculator>();

// Act
int actual = calculator.Sum(1, 2);
Expand All @@ -60,20 +51,13 @@ public class CalculatorTests
}
}

public sealed class Calculator
public sealed class Calculator(ILogger<Calculator> logger)
{
private readonly ILogger _logger;

public Calculator(ILogger<Calculator> logger)
{
_logger = logger;
}

public int Sum(int x, int y)
{
int sum = x + y;

_logger.LogInformation("The sum of {x} and {y} is {sum}.", x, y, sum);
logger.LogInformation("The sum of {x} and {y} is {sum}.", x, y, sum);

return sum;
}
Expand All @@ -98,7 +82,7 @@ This project is licensed under the [Apache 2.0](http://www.apache.org/licenses/L

## Building and Testing

Compiling the library yourself requires Git and the [.NET SDK](https://www.microsoft.com/net/download/core "Download the .NET SDK") to be installed (version `7.0.100` or later).
Compiling the library yourself requires Git and the [.NET SDK](https://www.microsoft.com/net/download/core "Download the .NET SDK") to be installed (version `8.0.100` or later).

To build and test the library locally from a terminal/command-line, run one of the following set of commands:

Expand Down
12 changes: 2 additions & 10 deletions build.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
#Requires -Version 7

param(
[Parameter(Mandatory = $false)][string] $Configuration = "Release",
[Parameter(Mandatory = $false)][string] $OutputPath = "",
[Parameter(Mandatory = $false)][switch] $SkipTests
)

Expand All @@ -27,10 +25,6 @@ $testProjects = @(

$dotnetVersion = (Get-Content $sdkFile | Out-String | ConvertFrom-Json).sdk.version

if ($OutputPath -eq "") {
$OutputPath = Join-Path $PSScriptRoot "artifacts"
}

$installDotNetSdk = $false;

if (($null -eq (Get-Command "dotnet" -ErrorAction SilentlyContinue)) -and ($null -eq (Get-Command "dotnet.exe" -ErrorAction SilentlyContinue))) {
Expand Down Expand Up @@ -88,9 +82,7 @@ if ($installDotNetSdk -eq $true) {
function DotNetPack {
param([string]$Project)

$PackageOutputPath = (Join-Path $OutputPath "packages")

& $dotnet pack $Project --output $PackageOutputPath --configuration $Configuration --include-symbols --include-source
& $dotnet pack $Project --include-symbols --include-source --tl

if ($LASTEXITCODE -ne 0) {
throw "dotnet pack failed with exit code $LASTEXITCODE"
Expand All @@ -107,7 +99,7 @@ function DotNetTest {
$additionalArgs += "GitHubActions;report-warnings=false"
}

& $dotnet test $Project --output $OutputPath --configuration $Configuration $additionalArgs
& $dotnet test $Project --configuration "Release" --tl $additionalArgs

if ($LASTEXITCODE -ne 0) {
throw "dotnet test failed with exit code $LASTEXITCODE"
Expand Down
2 changes: 1 addition & 1 deletion global.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"sdk": {
"version": "7.0.403",
"version": "8.0.100",
"allowPrerelease": false,
"rollForward": "latestMajor"
}
Expand Down
2 changes: 0 additions & 2 deletions src/Logging.XUnit/AmbientTestOutputHelperAccessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ internal sealed class AmbientTestOutputHelperAccessor : ITestOutputHelperAccesso
/// </summary>
private static readonly AsyncLocal<ITestOutputHelper?> _current = new();

#pragma warning disable CA1822
/// <summary>
/// Gets or sets the current <see cref="ITestOutputHelper"/>.
/// </summary>
Expand All @@ -25,5 +24,4 @@ public ITestOutputHelper? OutputHelper
get { return _current.Value; }
set { _current.Value = value; }
}
#pragma warning restore CA1822
}
23 changes: 9 additions & 14 deletions src/Logging.XUnit/MessageSinkAccessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,17 @@ namespace MartinCostello.Logging.XUnit;
/// <summary>
/// A class representing the default implementation of <see cref="IMessageSinkAccessor"/>. This class cannot be inherited.
/// </summary>
internal sealed class MessageSinkAccessor : IMessageSinkAccessor
/// <remarks>
/// Initializes a new instance of the <see cref="MessageSinkAccessor"/> class.
/// </remarks>
/// <param name="messageSink">The <see cref="IMessageSink"/> to use.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="messageSink"/> is <see langword="null"/>.
/// </exception>
internal sealed class MessageSinkAccessor(IMessageSink messageSink) : IMessageSinkAccessor
{
/// <summary>
/// Initializes a new instance of the <see cref="MessageSinkAccessor"/> class.
/// </summary>
/// <param name="messageSink">The <see cref="IMessageSink"/> to use.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="messageSink"/> is <see langword="null"/>.
/// </exception>
internal MessageSinkAccessor(IMessageSink messageSink)
{
MessageSink = messageSink ?? throw new ArgumentNullException(nameof(messageSink));
}

/// <summary>
/// Gets or sets the current <see cref="IMessageSink"/>.
/// </summary>
public IMessageSink? MessageSink { get; set; }
public IMessageSink? MessageSink { get; set; } = messageSink ?? throw new ArgumentNullException(nameof(messageSink));
}
15 changes: 4 additions & 11 deletions src/Logging.XUnit/StringSyntaxAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,17 @@ namespace System.Diagnostics.CodeAnalysis;

[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
[ExcludeFromCodeCoverage]
internal sealed class StringSyntaxAttribute : Attribute
internal sealed class StringSyntaxAttribute(string syntax, params object?[] arguments) : Attribute
{
public const string DateTimeFormat = nameof(DateTimeFormat);

public StringSyntaxAttribute(string syntax)
: this(syntax, [])
{
Syntax = syntax;
Arguments = Array.Empty<object?>();
}

public StringSyntaxAttribute(string syntax, params object?[] arguments)
{
Syntax = syntax;
Arguments = arguments;
}

public string Syntax { get; }
public string Syntax { get; } = syntax;

public object?[] Arguments { get; }
public object?[] Arguments { get; } = arguments;
}
#endif
23 changes: 9 additions & 14 deletions src/Logging.XUnit/TestOutputHelperAccessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,17 @@ namespace MartinCostello.Logging.XUnit;
/// <summary>
/// A class representing the default implementation of <see cref="ITestOutputHelperAccessor"/>. This class cannot be inherited.
/// </summary>
internal sealed class TestOutputHelperAccessor : ITestOutputHelperAccessor
/// <remarks>
/// Initializes a new instance of the <see cref="TestOutputHelperAccessor"/> class.
/// </remarks>
/// <param name="outputHelper">The <see cref="ITestOutputHelper"/> to use.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="outputHelper"/> is <see langword="null"/>.
/// </exception>
internal sealed class TestOutputHelperAccessor(ITestOutputHelper outputHelper) : ITestOutputHelperAccessor
{
/// <summary>
/// Initializes a new instance of the <see cref="TestOutputHelperAccessor"/> class.
/// </summary>
/// <param name="outputHelper">The <see cref="ITestOutputHelper"/> to use.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="outputHelper"/> is <see langword="null"/>.
/// </exception>
internal TestOutputHelperAccessor(ITestOutputHelper outputHelper)
{
OutputHelper = outputHelper ?? throw new ArgumentNullException(nameof(outputHelper));
}

/// <summary>
/// Gets or sets the current <see cref="ITestOutputHelper"/>.
/// </summary>
public ITestOutputHelper? OutputHelper { get; set; }
public ITestOutputHelper? OutputHelper { get; set; } = outputHelper ?? throw new ArgumentNullException(nameof(outputHelper));
}
17 changes: 6 additions & 11 deletions src/Logging.XUnit/XUnitLogScope.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,21 @@ namespace MartinCostello.Logging.XUnit;
/// <summary>
/// A class representing a scope for logging. This class cannot be inherited.
/// </summary>
internal sealed class XUnitLogScope
/// <remarks>
/// Initializes a new instance of the <see cref="XUnitLogScope"/> class.
/// </remarks>
/// <param name="state">The state object for the scope.</param>
internal sealed class XUnitLogScope(object state)
{
/// <summary>
/// The scope for the current thread.
/// </summary>
private static readonly AsyncLocal<XUnitLogScope?> _value = new();

/// <summary>
/// Initializes a new instance of the <see cref="XUnitLogScope"/> class.
/// </summary>
/// <param name="state">The state object for the scope.</param>
internal XUnitLogScope(object state)
{
State = state;
}

/// <summary>
/// Gets the state object for the scope.
/// </summary>
public object State { get; }
public object State { get; } = state;

/// <summary>
/// Gets or sets the current scope.
Expand Down
10 changes: 2 additions & 8 deletions src/Logging.XUnit/XUnitLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -151,10 +151,7 @@ public virtual void WriteMessage(LogLevel logLevel, int eventId, string? message
StringBuilder? logBuilder = _logBuilder;
_logBuilder = null;

if (logBuilder == null)
{
logBuilder = new StringBuilder();
}
logBuilder ??= new StringBuilder();

string logLevelString = GetLogLevelString(logLevel);

Expand Down Expand Up @@ -202,10 +199,7 @@ public virtual void WriteMessage(LogLevel logLevel, int eventId, string? message

try
{
if (outputHelper != null)
{
outputHelper.WriteLine(line);
}
outputHelper?.WriteLine(line);

if (messageSink != null)
{
Expand Down
Loading

0 comments on commit 53f94ee

Please sign in to comment.