簡體   English   中英

如何配置 C# 解決方案以在任何代碼樣式違規時失敗?

[英]How to configure C# solutions to fail on any code style violations?

我創建了一個示例 Web API 項目,並希望在我的 CI 管道期間強制執行編碼約定(如果在開發過程中出現樣式錯誤,則可以加分)。 基本上我只想為 C# 項目設置 eslint(來自 JavaScript 世界)。

我想在解決方案范圍內強制執行這些規則,所以我在根目錄中添加了一個Directory.Build.props文件,其中包含以下內容(我想使用Roslyn 分析器並在警告中失敗)

<Project>
  <PropertyGroup Label="Compiler Settings">
     <EnableNETAnalyzers>true</EnableNETAnalyzers>
     <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
     <AnalysisMode>AllEnabledByDefault</AnalysisMode>
     <AnalysisLevel>latest</AnalysisLevel>
     <WarningLevel>5</WarningLevel>
  </PropertyGroup>
</Project>

接下來,我安裝了dotnet 格式以訪問dotnet format ./MySln.sln --verify-no-changes命令。

我將生成的WeatherForecastController修改為

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() { }
}

運行格式命令時,我預計會出現以下情況,其中一些已被識別

  • System的冗余導入❌
  • 永遠不會使用Summaries
  • Summaries的冗余數組創建表達式 ❌
  • _logger從未使用過 ❌
  • 從未unused過 ✅
  • WeatherForecast的冗余類型規范 ❌
  • 空格錯誤✅
  • 刪除Get方法中的空行 ❌
  • 修復Get方法中的縮進 ❌
  • 方法Do從未使用過 ❌

我認為我缺少的一件事是 .editorconfig 文件? 我將Roslyn Analyzers .editorconfig復制粘貼到我的項目中,這有點幫助(它沒有抓住所有這些)

如果我的方法是正確的方法,有什么可以改進的嗎? Directory.Build.props文件)並且有一個官方的超級嚴格的 .editorconfig 嗎?

如果我的方法是錯誤的,那么在 C# 世界中解決這個問題的正確方法是什么?

提前致謝

使用 R# 命令行工具無法實現的 AFAIK。

對於 Roslyn 分析器,它可以幫助在您的csproj文件中設置TreatWarningsAsErrors

<PropertyGroup>
  <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>

不要更改您的.csproj文件。 在解決方案目錄中,添加一個Directory.Build.props文件,其中包含以下內容:

<Project>
  <PropertyGroup Label="Compiler Settings">
     <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
     <AnalysisMode>AllEnabledByDefault</AnalysisMode>
     <WarningLevel>5</WarningLevel>
  </PropertyGroup>
</Project>

根據您的需要調整設置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM