aliyasar/dotnet-arch-analyzer

GitHub: aliyasar/dotnet-arch-analyzer

一款无需构建的 .NET 静态架构分析工具,通过可配置规则检查分层违规、循环依赖和代码复杂度问题。

Stars: 2 | Forks: 0

# dotnet-arch `dotnet-arch` 使用 Roslyn 对 C# 代码库进行静态分析。它无需构建即可执行架构规则检查、检测代码质量问题并生成依赖关系图。 ## 安装 ``` dotnet tool install -g dotnet-arch ``` 需要 [.NET 8 SDK](https://dotnet.microsoft.com/download) 或更高版本。 ## 快速开始 ``` # 分析当前目录 dotnet-arch analyze . # 列出所有活动规则及其阈值 dotnet-arch rules . # 生成 Mermaid 依赖关系图 dotnet-arch graph ./src/MyApp # 创建配置文件 dotnet-arch init . ``` ## 输出 ``` Architecture Analysis Grade: A 91/100 ──────────────────────────────────────────────────────────────── Types 28 Methods 46 Dependencies 22 Violations 3 complexity/method-length (1 warning) ──────────────────────────────────────────────────────────────── Parsing\RoslynParser.cs 27 ⚠ RoslynParser.ParseFile is 83 lines long (threshold: 60) Rule summary ──────────────────────────────────────────────────────────────── complexity/method-length 1 warning ✖ 1 problem (0 errors, 1 warning) ``` 违规项按规则分组。每项违规都会显示文件、行号和简短描述。 ## 规则 ### Architecture | 规则 | 默认级别 | 描述 | |----------------------------|----------|----------------------------------------------------------| | `arch/layer-violation` | warning | 较低层级(如 Domain)引用了较高层级(如 Infrastructure) | | `arch/circular-dependency` | error | 两个或多个命名空间形成依赖循环 | | `arch/high-coupling` | warning | 某个类型依赖于过多的命名空间 | ### Style | 规则 | 默认级别 | 描述 | |----------------------------|----------|----------------------------------------------------------| | `style/interface-prefix` | warning | 接口名称应以 `I` 开头 | | `style/async-suffix` | warning | Async 方法名称应以 `Async` 结尾 | | `style/no-empty-catch` | warning | 空的 catch 块会静默吞掉异常 | | `style/namespace-match` | warning | 命名空间应与其所在的文件夹匹配 | ### Complexity | 规则 | 默认级别 | 阈值 | 描述 | |------------------------------|----------|-----------|------------------------------------------| | `complexity/method-length` | warning | 40 行 | 方法过长 | | `complexity/class-length` | warning | 300 行 | 类过长 | | `complexity/parameter-count` | warning | 5 | 方法参数过多 | | `complexity/cyclomatic` | warning | 10 | 决策路径(if/for/catch…)过多 | | `complexity/nesting-depth` | warning | 4 | 嵌套块过多 | 任何规则均可在配置文件中设置为 `"error"`、`"warning"` 或 `"off"`。 ## 配置 运行 `dotnet-arch init .` 在项目根目录下生成 `dotnetarch.json`: ``` { // Layer keywords matched against namespace segments (case-insensitive) "layers": { "domain": ["models", "entities", "dto", "exceptions"], "application": ["services", "handlers"], "infrastructure": ["repositories", "context", "dataaccess"], "web": ["controllers"] }, // Rule severity: "error" | "warning" | "off" "rules": { "arch/layer-violation": "warning", "arch/circular-dependency": "error", "style/no-empty-catch": "warning", "complexity/method-length": "warning", "complexity/cyclomatic": "off" }, // Numeric thresholds — see table below for guidance "thresholds": { "complexity/method-length": 40, "complexity/cyclomatic": 10, "complexity/nesting-depth": 4 } } ``` ### 阈值参考 | | Strict | Moderate | Lenient | |------------------------------|--------|----------|---------| | `arch/high-coupling` | 5 | 10 | 15 | | `complexity/method-length` | 20 | 40 | 80 | | `complexity/class-length` | 150 | 300 | 500 | | `complexity/parameter-count` | 3 | 5 | 8 | | `complexity/cyclomatic` | 5 | 10 | 20 | | `complexity/nesting-depth` | 2 | 4 | 6 | **Strict** = Clean Code 风格(短小、专注、易于测试) **Moderate** = 适用于大多数代码库的务实默认值 **Lenient** = 适用于迁移遗留代码库 您可以设置任意整数值 —— 此表仅供参考。 ## CI/CD `dotnet-arch` 专为在流水线中运行而设计。 ``` # GitHub Actions - name: Analyze architecture run: dotnet-arch analyze ./src --max-warnings 0 ``` ### 退出代码 | 代码 | 含义 | |------|------------------------------------------------| | `0` | 无错误,警告在阈值内 | | `1` | 存在一个或多个错误,或警告超过 `--max-warnings` | ### `--max-warnings` 如果警告超过限制则构建失败: ``` dotnet-arch analyze . --max-warnings 10 ``` ### GitHub Actions 批注 当在 GitHub Actions(`GITHUB_ACTIONS=true`)中运行时,违规会自动作为 PR 内联批注输出: ``` ::warning file=src/Services/UserService.cs,line=12::[style/no-empty-catch] Empty catch block... ``` ## 输出格式 ``` # 默认 — 彩色终端输出 dotnet-arch analyze . # JSON — 适用于工具和脚本 dotnet-arch analyze . --format json # 将 JSON 保存到文件 dotnet-arch analyze . --format json --output report.json ``` ## 忽略路径 在项目根目录下创建 `.archignore` 文件: ``` # 自动生成 Migrations/ Generated/ # Tests Tests/ ``` ## 工作原理 1. 使用 **Roslyn** 解析所有 `.cs` 文件(无需构建) 2. 提取类型、方法、命名空间和 `using` 指令 3. 将命名空间段映射到架构层 4. 对解析后的模型运行已注册的规则 5. 报告按规则分组的违规,包含文件和行号 ## 贡献 要添加新规则,请实现 `IArchRule`: ``` public sealed class MyRule : IArchRule { public string RuleId => "style/my-rule"; public IEnumerable Analyze( IReadOnlyList types, IReadOnlyList methods, ArchConfig config) { if (!config.IsRuleEnabled(RuleId)) yield break; var severity = config.GetSeverityOverride(RuleId) ?? ViolationSeverity.Warning; // your logic here } } ``` 然后在 `Program.cs` 中注册它: ``` services.AddSingleton(); ``` ## 许可证 MIT
标签:dotnet-tool, Mermaid, Roslyn, 云安全监控, 代码复杂度, 代码规范, 依赖图, 多人体追踪, 安全专业人员, 对称加密, 数据管道, 文档结构分析, 架构分析, 自动化审计, 软件工程, 静态分析