GitHub Super Linter如何自定义C#代码检查规则?
为GitHub Super Linter配置C#自定义规则
Super Linter针对C#的代码检查默认依赖dotnet-format和Roslyn分析器(如StyleCop Analyzers),虽然没有专门的环境变量指定规则文件,但可以通过项目本身的配置文件实现自定义规则,具体步骤如下:
1. 用.editorconfig配置dotnet-format规则
dotnet-format会自动读取仓库中的.editorconfig文件应用代码风格规则,你可以在仓库根目录或项目目录下创建/修改该文件,定义C#相关规则:
[*.cs] # 缩进配置 indent_size = 4 indent_style = space # 命名规范规则 dotnet_naming_rule.interface_should_be_begins_with_i.severity = warning dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface dotnet_naming_rule.interface_should_be_begins_with_i.style = interface_naming_style dotnet_naming_style.interface_naming_style.required_prefix = I
Super Linter运行时会自动识别该文件并执行对应规则检查。
2. 通过Roslyn分析器配置复杂规则
如果需要代码质量类的自定义规则(如潜在bug检查、代码规范约束),可以引入Roslyn分析器包并配置规则:
- 在项目的
.csproj文件中添加分析器依赖,以StyleCop Analyzers为例:
<ItemGroup> <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference> </ItemGroup>
- 创建
StyleCop.json定制规则,示例:
{ "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json", "settings": { "documentationRules": { "companyName": "你的公司名称", "copyrightText": "Copyright (c) {companyName}. All rights reserved." }, "namingRules": { "allowCommonHungarianPrefixes": false } } }
将该配置文件放在仓库根目录或项目目录,Super Linter会自动读取并应用规则。
3. 配置GitHub Action确保规则文件被识别
在Super Linter的Action配置中,无需额外C#专属环境变量,只需确保规则文件已提交到仓库。若规则文件在子目录,可通过全局的LINTER_RULES_PATH变量指定路径:
name: Super Linter on: [push, pull_request] jobs: lint: runs-on: ubuntu-latest steps: - name: 拉取代码 uses: actions/checkout@v4 with: fetch-depth: 0 - name: 运行Super Linter uses: github/super-linter@v5 env: DEFAULT_BRANCH: main GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} LINTER_RULES_PATH: ./config/linter-rules # 规则文件所在子目录,按需修改
验证规则生效
提交配置文件和测试代码到仓库,触发Action运行,查看Super Linter输出日志,违反自定义规则的代码会被检测并报错。
内容的提问来源于stack exchange,提问作者bitsandgates
相关产品推荐
相关产品推荐

