I created a sample Web API project and want to enforce coding conventions during my CI pipeline ( bonus points if the style errors come up during development ). Basically I just want to setup eslint ( from the JavaScript world ) for C# projects.
I want to enforce those rules solution wide so I added a Directory.Build.props file in the root directory with the following content ( I want to use the Roslyn Analyzers and fail on warnings )
<Project>
<PropertyGroup Label="Compiler Settings">
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AnalysisMode>AllEnabledByDefault</AnalysisMode>
<AnalysisLevel>latest</AnalysisLevel>
<WarningLevel>5</WarningLevel>
</PropertyGroup>
</Project>
Next I installed dotnet format to get access to the dotnet format ./MySln.sln --verify-no-changes command.
I modified the generated WeatherForecastController to
using Microsoft.AspNetCore.Mvc;
using System;
namespace LinterCheckSample.Controllers;
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
string unused = "";
return
new
List
<
WeatherForecast
>
()
{
new WeatherForecast() {}
};
}
private void Do() { }
}
When running the format command I expected the following things, some got identified
- Redundant import of
System❌ Summariesis never used ✅- Redundant array creation expression for
Summaries❌ _loggeris never used ❌unusedis never used ✅- Redundant type specification for
WeatherForecast❌ - Whitespace errors ✅
- Remove empty lines in
Getmethod ❌ - Fix indentation in
Getmethod ❌ - Method
Dois never used ❌
I think the one thing I'm missing is an .editorconfig file? I copy pasted the Roslyn Analyzers .editorconfig into my project and this helped a little bit ( it didn't catch all of them )
If my approach is the correct way is there something I can improve? ( Directory.Build.props file ) and is there one official super strict .editorconfig?
If my approach is wrong, what is the correct way to solve this in the C# world?
Thanks in advance