重构:完成架构一致性整改与生命周期收口
This commit is contained in:
1 parent
55904cc409
commit
9eb6be2875
344 files changed
+15961
-13926
No files matched your search
@@ -23,6 +23,30 @@ type violation struct {
|
||||
message string
|
||||
}
|
||||
|
||||
// controlledDynamicResponse 描述一个暂时保留的动态响应及其外部兼容治理条件。
|
||||
type controlledDynamicResponse struct {
|
||||
// matrixName 是兼容矩阵中必须出现的响应类型登记名。
|
||||
matrixName string
|
||||
// sunsetVersion 是该兼容响应计划移除的版本,必须与服务端遥测版本一致。
|
||||
sunsetVersion string
|
||||
}
|
||||
|
||||
// controlledDynamicResponses 是阶段 9 允许保留的最小动态响应登记表。
|
||||
var controlledDynamicResponses = map[string]controlledDynamicResponse{
|
||||
"settingsResponse": {
|
||||
matrixName: "settingsResponse",
|
||||
sunsetVersion: "v2.0",
|
||||
},
|
||||
"notificationBindingListResponse": {
|
||||
matrixName: "notificationBindingListResponse",
|
||||
sunsetVersion: "v2.0",
|
||||
},
|
||||
"automationRulePageResponse": {
|
||||
matrixName: "automationRulePageResponse",
|
||||
sunsetVersion: "v2.0",
|
||||
},
|
||||
}
|
||||
|
||||
// main 执行架构依赖检查并在发现违规时返回失败状态。
|
||||
func main() {
|
||||
// root 是待检查的仓库根目录。
|
||||
@@ -73,6 +97,7 @@ func checkRepository(root string) ([]violation, error) {
|
||||
violations = append(violations, fileViolations...)
|
||||
return nil
|
||||
})
|
||||
violations = append(violations, checkCompatibilityGovernance(root)...)
|
||||
return violations, walkErr
|
||||
}
|
||||
|
||||
@@ -121,6 +146,15 @@ func checkGoFile(root, relativePath string, fset *token.FileSet) ([]violation, e
|
||||
message: fmt.Sprintf("应用层禁止依赖基础设施或 HTTP 层 %q", importedPath),
|
||||
})
|
||||
}
|
||||
if isForbiddenHiddenDependencyImport(importPath, normalizedImport) {
|
||||
// line 是隐藏依赖导入所在的源码行号。
|
||||
line := fset.Position(imp.Pos()).Line
|
||||
violations = append(violations, violation{
|
||||
file: filepath.ToSlash(relativePath),
|
||||
line: line,
|
||||
message: fmt.Sprintf("业务与传输层禁止使用反射、插件或动态依赖隐藏必需装配 %q", importedPath),
|
||||
})
|
||||
}
|
||||
if isForbiddenServerLowLevelImport(importPath, normalizedImport) {
|
||||
// line 是 Server 新增低层依赖所在的源码行号。
|
||||
line := fset.Position(imp.Pos()).Line
|
||||
@@ -133,6 +167,9 @@ func checkGoFile(root, relativePath string, fset *token.FileSet) ([]violation, e
|
||||
}
|
||||
violations = append(violations, checkApplicationTypeLeaks(relativePath, syntax, fset)...)
|
||||
violations = append(violations, checkHTTPResponseContracts(relativePath, syntax, fset)...)
|
||||
violations = append(violations, checkHTTPRequestContracts(relativePath, syntax, fset)...)
|
||||
violations = append(violations, checkRuntimeSetterCalls(relativePath, syntax, fset)...)
|
||||
violations = append(violations, checkServerCompositionCalls(relativePath, syntax, fset)...)
|
||||
if strings.HasPrefix(filepath.ToSlash(relativePath), "internal/server/") && !strings.HasSuffix(relativePath, "_repository.go") {
|
||||
// sourceLine 是裸 BeginTx 调用首次出现的源码行号。
|
||||
sourceLine := firstLineContaining(string(source), ".DB.BeginTx(")
|
||||
@@ -147,6 +184,134 @@ func checkGoFile(root, relativePath string, fset *token.FileSet) ([]violation, e
|
||||
return violations, nil
|
||||
}
|
||||
|
||||
// checkServerCompositionCalls 禁止已迁出的应用 worker 组合逻辑回流到 Server transport 包。
|
||||
func checkServerCompositionCalls(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
// normalizedPath 是统一使用斜杠的仓库相对路径。
|
||||
normalizedPath := filepath.ToSlash(relativePath)
|
||||
if !strings.HasPrefix(normalizedPath, "internal/server/") || strings.HasSuffix(normalizedPath, "_test.go") {
|
||||
return nil
|
||||
}
|
||||
// forbiddenConstructors 记录必须由进程组合根创建的应用 worker 构造函数及修复提示。
|
||||
forbiddenConstructors := map[string]string{
|
||||
"NewReconciliationRecoveryCoordinator": "订单补偿恢复协调器必须由 cmd 组合根构造后注入 Server",
|
||||
"NewDatabaseHealth": "数据库健康检查端口必须由 cmd 组合根构造后注入 Server",
|
||||
}
|
||||
// violations 保存当前 Server 文件中发现的组合根回流问题。
|
||||
var violations []violation
|
||||
ast.Inspect(syntax, func(node ast.Node) bool {
|
||||
// call 是当前待检查的函数调用节点。
|
||||
call, ok := node.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// selector 是包函数或对象方法调用;仅包级构造函数可能违反本规则。
|
||||
selector, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// message 是命中构造函数后返回的组合根迁移提示。
|
||||
message, forbidden := forbiddenConstructors[selector.Sel.Name]
|
||||
if !forbidden {
|
||||
return true
|
||||
}
|
||||
violations = append(violations, violation{
|
||||
file: normalizedPath,
|
||||
line: fset.Position(call.Pos()).Line,
|
||||
message: message,
|
||||
})
|
||||
return true
|
||||
})
|
||||
return violations
|
||||
}
|
||||
|
||||
// checkHTTPRequestContracts 禁止 Server handler 使用匿名请求结构,保证请求契约能够被复用、审计和版本化。
|
||||
func checkHTTPRequestContracts(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
// normalizedPath 是统一使用斜杠的仓库相对路径。
|
||||
normalizedPath := filepath.ToSlash(relativePath)
|
||||
if !strings.HasPrefix(normalizedPath, "internal/server/") || strings.HasSuffix(normalizedPath, "_test.go") || !strings.HasSuffix(normalizedPath, "_handlers.go") {
|
||||
return nil
|
||||
}
|
||||
// violations 保存当前 handler 文件中发现的匿名请求结构。
|
||||
var violations []violation
|
||||
ast.Inspect(syntax, func(node ast.Node) bool {
|
||||
// declaration 是函数体内可能包含请求变量的声明语句。
|
||||
declaration, ok := node.(*ast.DeclStmt)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// generalDeclaration 是具体的 var 声明;短变量声明不会承载匿名 struct 类型。
|
||||
generalDeclaration, ok := declaration.Decl.(*ast.GenDecl)
|
||||
if !ok || generalDeclaration.Tok != token.VAR {
|
||||
return true
|
||||
}
|
||||
// specification 是当前 var 声明中的单个语法规格。
|
||||
for _, specification := range generalDeclaration.Specs {
|
||||
// valueSpecification 是当前 var 声明的名称、类型和初始值组合。
|
||||
valueSpecification, ok := specification.(*ast.ValueSpec)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
// anonymousStruct 表示该变量是否直接声明为匿名 struct 类型。
|
||||
_, anonymousStruct := valueSpecification.Type.(*ast.StructType)
|
||||
if !anonymousStruct {
|
||||
continue
|
||||
}
|
||||
// name 是当前匿名结构声明中的变量名。
|
||||
for _, name := range valueSpecification.Names {
|
||||
if name.Name != "req" && name.Name != "input" {
|
||||
continue
|
||||
}
|
||||
violations = append(violations, violation{
|
||||
file: normalizedPath,
|
||||
line: fset.Position(valueSpecification.Pos()).Line,
|
||||
message: fmt.Sprintf("HTTP 请求变量 %s 禁止使用匿名 struct,请定义具名 DTO", name.Name),
|
||||
})
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
return violations
|
||||
}
|
||||
|
||||
// checkRuntimeSetterCalls 禁止生产代码调用仅为测试替身保留的 Adapter 运行时 setter。
|
||||
func checkRuntimeSetterCalls(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
// normalizedPath 是统一使用斜杠的仓库相对路径。
|
||||
normalizedPath := filepath.ToSlash(relativePath)
|
||||
if strings.HasSuffix(normalizedPath, "_test.go") {
|
||||
return nil
|
||||
}
|
||||
// testOnlySetters 是已登记为测试隔离入口的 Adapter setter 名称。
|
||||
testOnlySetters := map[string]struct{}{
|
||||
"SetAutomation": {}, "SetNotifier": {}, "SetChatService": {}, "SetCredentialWakeService": {},
|
||||
"SetBrowser": {}, "SetRenewService": {}, "SetTokenCaptchaRequester": {}, "SetOrderDetailClient": {},
|
||||
}
|
||||
// violations 保存生产代码绕过构造期依赖固定的调用位置。
|
||||
var violations []violation
|
||||
ast.Inspect(syntax, func(node ast.Node) bool {
|
||||
// call 是当前待判断的函数调用节点。
|
||||
call, ok := node.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// selector 是当前调用的选择器表达式,只有明确的 Adapter setter 名称才属于本规则。
|
||||
selector, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// registered 表示当前调用是否属于明确登记的测试兼容 setter。
|
||||
if _, registered := testOnlySetters[selector.Sel.Name]; !registered {
|
||||
return true
|
||||
}
|
||||
violations = append(violations, violation{
|
||||
file: normalizedPath,
|
||||
line: fset.Position(call.Pos()).Line,
|
||||
message: fmt.Sprintf("生产代码禁止调用测试兼容 setter %s,请通过构造期 RuntimeBundle 注入", selector.Sel.Name),
|
||||
})
|
||||
return true
|
||||
})
|
||||
return violations
|
||||
}
|
||||
|
||||
// checkHTTPResponseContracts 检查 Server 对外响应是否使用具名 DTO,并阻止动态 map 绕过契约边界。
|
||||
func checkHTTPResponseContracts(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
// normalizedPath 是统一使用斜杠的仓库相对路径。
|
||||
@@ -192,13 +357,64 @@ func checkHTTPResponseContracts(relativePath string, syntax *ast.File, fset *tok
|
||||
|
||||
// isControlledDynamicResponseType 判断已登记的动态键兼容响应,避免本阶段改变旧客户端 JSON 形状。
|
||||
func isControlledDynamicResponseType(name string) bool {
|
||||
// 这些类型的键来自账号 ID、触发类型或设置名称;只有完成外部调用方审计后才允许在后续阶段删除。
|
||||
switch name {
|
||||
case "settingsResponse", "notificationBindingListResponse", "automationRulePageResponse":
|
||||
return true
|
||||
default:
|
||||
// ok 表示响应类型是否已在阶段 9 的兼容登记表中备案。
|
||||
_, ok := controlledDynamicResponses[name]
|
||||
return ok
|
||||
}
|
||||
|
||||
// isForbiddenHiddenDependencyImport 禁止应用与 Server 通过反射、插件机制或动态加载隐藏必需依赖。
|
||||
func isForbiddenHiddenDependencyImport(filePath, importedPath string) bool {
|
||||
// productionLayer 表示阶段 9 需要封死隐式装配旁路的生产层。
|
||||
productionLayer := (strings.HasPrefix(filePath, "internal/application/") && !strings.HasSuffix(filePath, "_test.go")) ||
|
||||
(strings.HasPrefix(filePath, "internal/server/") && !strings.HasSuffix(filePath, "_test.go"))
|
||||
if !productionLayer {
|
||||
return false
|
||||
}
|
||||
for _, forbidden /* forbidden 是禁止隐藏依赖实现的标准库或运行时包名。 */ := range []string{"reflect", "plugin", "unsafe"} {
|
||||
if importedPath == forbidden || strings.HasPrefix(importedPath, forbidden+"/") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// checkCompatibilityGovernance 校验动态响应白名单、Sunset 版本与运行时遥测保持同步。
|
||||
func checkCompatibilityGovernance(root string) []violation {
|
||||
// matrixPath 是记录外部调用方、删除条件和 Sunset 版本的兼容矩阵路径。
|
||||
matrixPath := filepath.Join(root, "docs", "architecture", "api-compatibility-matrix.md")
|
||||
// matrixBytes 是兼容矩阵原文,用于避免白名单脱离文档治理。
|
||||
matrixBytes, err := os.ReadFile(matrixPath)
|
||||
if err != nil {
|
||||
return []violation{{file: filepath.ToSlash(filepath.Join("docs", "architecture", "api-compatibility-matrix.md")), line: 1, message: fmt.Sprintf("无法读取兼容矩阵: %v", err)}}
|
||||
}
|
||||
// matrix 是兼容矩阵文本,统一使用字符串匹配保留文档格式独立性。
|
||||
matrix := string(matrixBytes)
|
||||
// serverPath 是定义历史 API 遥测版本的服务端文件路径。
|
||||
serverPath := filepath.Join(root, "internal", "server", "server.go")
|
||||
// serverBytes 是服务端源码,用于确认每个兼容响应共用实际遥测版本。
|
||||
serverBytes, err := os.ReadFile(serverPath)
|
||||
if err != nil {
|
||||
return []violation{{file: filepath.ToSlash(filepath.Join("internal", "server", "server.go")), line: 1, message: fmt.Sprintf("无法读取历史 API 遥测实现: %v", err)}}
|
||||
}
|
||||
// serverSource 是服务端源码文本,供版本与弃用头检查使用。
|
||||
serverSource := string(serverBytes)
|
||||
// violations 保存兼容治理缺失或版本漂移问题。
|
||||
var violations []violation
|
||||
for name /* name 是当前受控动态响应的 Go 类型名。 */, registration /* registration 是该响应的矩阵登记与退场版本。 */ := range controlledDynamicResponses {
|
||||
if !strings.Contains(matrix, "`"+registration.matrixName+"`") && !strings.Contains(matrix, registration.matrixName) {
|
||||
violations = append(violations, violation{file: "docs/architecture/api-compatibility-matrix.md", line: 1, message: fmt.Sprintf("动态响应 %s 未登记在兼容矩阵", name)})
|
||||
}
|
||||
if !strings.Contains(matrix, registration.sunsetVersion) {
|
||||
violations = append(violations, violation{file: "docs/architecture/api-compatibility-matrix.md", line: 1, message: fmt.Sprintf("动态响应 %s 缺少 Sunset 版本 %s", name, registration.sunsetVersion)})
|
||||
}
|
||||
}
|
||||
if !strings.Contains(serverSource, `legacyAPISuccessorLink = "</api/v1>; rel=\"successor-version\"; title=\"v2.0\""`) {
|
||||
violations = append(violations, violation{file: "internal/server/server.go", line: 1, message: "历史 API successor Link 必须声明与兼容矩阵一致的版本 v2.0"})
|
||||
}
|
||||
if !strings.Contains(serverSource, `legacyAPISunsetDate = `) || !strings.Contains(serverSource, `Header().Set("Deprecation", "true")`) || !strings.Contains(serverSource, `Header().Set("Sunset", legacyAPISunsetDate)`) {
|
||||
violations = append(violations, violation{file: "internal/server/server.go", line: 1, message: "历史 API 必须写入 Deprecation 与 Sunset 遥测头"})
|
||||
}
|
||||
return violations
|
||||
}
|
||||
|
||||
// isHTTPContractTypeName 判断类型名称是否属于 Server 的 HTTP 响应契约。
|
||||
|
||||
@@ -81,6 +81,37 @@ type testResponse map[string]any
|
||||
}
|
||||
}
|
||||
|
||||
// TestHTTPRequestContractBoundary 验证 handler 请求体必须使用具名 DTO,避免匿名结构绕过版本化契约。
|
||||
func TestHTTPRequestContractBoundary(t *testing.T) {
|
||||
// fset 是模拟 Server handler 文件的源码位置集合。
|
||||
fset := token.NewFileSet()
|
||||
// syntax、err 分别是包含匿名请求结构的模拟 handler AST 及解析错误。
|
||||
syntax, err := parser.ParseFile(fset, "request_handlers.go", []byte(`package server
|
||||
func handler() { var req struct { Value string }; _ = req }
|
||||
`), parser.ParseComments)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// violations 是匿名请求 DTO 应产生的架构违规。
|
||||
violations := checkHTTPRequestContracts("internal/server/request_handlers.go", syntax, fset)
|
||||
if len(violations) != 1 {
|
||||
t.Fatalf("violations=%+v", violations)
|
||||
}
|
||||
// cleanSyntax、cleanErr 分别是使用具名请求 DTO 的模拟 handler AST 及解析错误。
|
||||
cleanSyntax, cleanErr := parser.ParseFile(fset, "clean_handlers.go", []byte(`package server
|
||||
type requestDTO struct { Value string }
|
||||
func handler() { var req requestDTO; _ = req }
|
||||
`), parser.ParseComments)
|
||||
if cleanErr != nil {
|
||||
t.Fatal(cleanErr)
|
||||
}
|
||||
// cleanViolations 是具名 DTO 应保持为零的架构违规集合。
|
||||
cleanViolations := checkHTTPRequestContracts("internal/server/clean_handlers.go", cleanSyntax, fset)
|
||||
if len(cleanViolations) != 0 {
|
||||
t.Fatalf("clean violations=%+v", cleanViolations)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNormalizeImportPath 验证架构检查器能够识别当前模块的内部包路径。
|
||||
func TestNormalizeImportPath(t *testing.T) {
|
||||
if got /* got 是规范化后的导入路径。 */ := normalizeImportPath("xianyu-go/internal/db"); got != "internal/db" {
|
||||
@@ -123,6 +154,78 @@ func TestServerLowLevelBoundary(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestHiddenDependencyBoundary 验证生产应用与 Server 不得通过反射或插件隐藏必需依赖。
|
||||
func TestHiddenDependencyBoundary(t *testing.T) {
|
||||
if !isForbiddenHiddenDependencyImport("internal/application/orders/service.go", "reflect") {
|
||||
t.Fatal("应用层 reflect 依赖应被拒绝")
|
||||
}
|
||||
if !isForbiddenHiddenDependencyImport("internal/server/server.go", "plugin") {
|
||||
t.Fatal("Server plugin 依赖应被拒绝")
|
||||
}
|
||||
if isForbiddenHiddenDependencyImport("internal/adapter/adapter_test.go", "reflect") {
|
||||
t.Fatal("测试或适配层 reflect 依赖不应被本规则阻断")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRuntimeSetterBoundary 验证生产调用不能通过 Adapter setter 延迟补齐必需依赖。
|
||||
func TestRuntimeSetterBoundary(t *testing.T) {
|
||||
// fset 是模拟生产源码的文件位置集合。
|
||||
fset := token.NewFileSet()
|
||||
// syntax、err 是包含测试兼容 setter 调用的模拟生产文件。
|
||||
syntax, err := parser.ParseFile(fset, "runtime.go", []byte(`package main
|
||||
func run(adapter any) { adapter.SetAutomation(nil) }
|
||||
`), parser.ParseComments)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// violations 是生产 setter 调用的扫描结果。
|
||||
violations := checkRuntimeSetterCalls("cmd/server/runtime.go", syntax, fset)
|
||||
if len(violations) != 1 {
|
||||
t.Fatalf("violations=%+v", violations)
|
||||
}
|
||||
// testSyntax 是测试文件中的同一调用,测试替身可以继续使用兼容 setter。
|
||||
testSyntax, err := parser.ParseFile(fset, "runtime_test.go", []byte(`package main
|
||||
func test(adapter any) { adapter.SetAutomation(nil) }
|
||||
`), parser.ParseComments)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// got 是测试文件中的 setter 调用扫描结果。
|
||||
if got := checkRuntimeSetterCalls("cmd/server/runtime_test.go", testSyntax, fset); len(got) != 0 {
|
||||
t.Fatalf("测试 setter 不应被阻断: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestServerCompositionBoundary 验证已迁出的应用 worker 不会回流到 Server transport 构造阶段。
|
||||
func TestServerCompositionBoundary(t *testing.T) {
|
||||
// fset 是模拟 Server 源码的文件位置集合。
|
||||
fset := token.NewFileSet()
|
||||
// syntax、err 分别是包含禁止应用 worker 与健康端口构造的模拟 Server 文件及解析错误。
|
||||
syntax, err := parser.ParseFile(fset, "composition.go", []byte(`package server
|
||||
func build() { orderapp.NewReconciliationRecoveryCoordinator(nil); adapter.NewDatabaseHealth(nil) }
|
||||
`), parser.ParseComments)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// violations 是迁移回流应产生的架构违规。
|
||||
violations := checkServerCompositionCalls("internal/server/composition.go", syntax, fset)
|
||||
if len(violations) != 2 {
|
||||
t.Fatalf("violations=%+v", violations)
|
||||
}
|
||||
// cleanSyntax、cleanErr 分别是仅接收已构造服务的合规 Server 文件及解析错误。
|
||||
cleanSyntax, cleanErr := parser.ParseFile(fset, "composition_clean.go", []byte(`package server
|
||||
func accept(service any) { _ = service }
|
||||
`), parser.ParseComments)
|
||||
if cleanErr != nil {
|
||||
t.Fatal(cleanErr)
|
||||
}
|
||||
// cleanViolations 是合规 Server 文件应保持为空的违规集合。
|
||||
cleanViolations := checkServerCompositionCalls("internal/server/composition_clean.go", cleanSyntax, fset)
|
||||
if len(cleanViolations) != 0 {
|
||||
t.Fatalf("clean violations=%+v", cleanViolations)
|
||||
}
|
||||
}
|
||||
|
||||
// TestApplicationTypeLeakBoundary 验证应用 Port 类型扫描会拒绝基础设施和 Server 类型。
|
||||
func TestApplicationTypeLeakBoundary(t *testing.T) {
|
||||
// fset 是测试源代码的文件位置集合。
|
||||
|
||||
+120
-90
@@ -2,7 +2,6 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"go/ast"
|
||||
@@ -10,6 +9,7 @@ import (
|
||||
"go/token"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"unicode"
|
||||
@@ -27,14 +27,29 @@ type Finding struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// main 根据命令行模式生成历史基线或检查当前源码。
|
||||
// templateCommentPattern 描述一种没有解释实际语义的机械注释模式。
|
||||
type templateCommentPattern struct {
|
||||
// name 是输出给维护者的模板类别。
|
||||
name string
|
||||
// expression 匹配整条注释中的占位句式。
|
||||
expression *regexp.Regexp
|
||||
}
|
||||
|
||||
// templateCommentPatterns 是阶段 10 必须清除的历史占位注释集合。
|
||||
var templateCommentPatterns = []templateCommentPattern{
|
||||
{name: "保存当前处理流程", expression: regexp.MustCompile(`保存.{0,80}供当前处理流程使用`)},
|
||||
{name: "负责相关处理", expression: regexp.MustCompile(`负责.{0,80}相关处理`)},
|
||||
{name: "泛化回调职责", expression: regexp.MustCompile(`回调函数负责当前业务流程`)},
|
||||
{name: "泛化错误说明", expression: regexp.MustCompile(`表示错误`)},
|
||||
{name: "泛化数量说明", expression: regexp.MustCompile(`表示数量`)},
|
||||
}
|
||||
|
||||
// main 运行严格注释门禁或输出模板注释审计结果。
|
||||
func main() {
|
||||
// modeFlag 表示本次运行是生成基线还是执行门禁检查。
|
||||
modeFlag := flag.String("mode", "check", "运行模式:check 或 baseline")
|
||||
// modeFlag 表示本次运行是执行严格门禁或仅输出模板审计结果。
|
||||
modeFlag := flag.String("mode", "check", "运行模式:check 或 template-audit")
|
||||
// rootFlag 指定需要递归扫描的仓库根目录。
|
||||
rootFlag := flag.String("root", ".", "源码扫描根目录")
|
||||
// baselineFlag 指定保存或读取历史问题基线的 JSON 文件。
|
||||
baselineFlag := flag.String("baseline", ".commentlint/go-baseline.json", "历史问题基线文件")
|
||||
flag.Parse()
|
||||
|
||||
// findings 保存本次扫描发现的全部缺少中文注释项。
|
||||
@@ -43,40 +58,45 @@ func main() {
|
||||
fmt.Fprintf(os.Stderr, "commentlint: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// sortFindings 保证基线内容和门禁输出在不同机器上保持稳定顺序。
|
||||
sortFindings(findings)
|
||||
if *modeFlag == "baseline" {
|
||||
// writeErr 保存写入历史基线时的文件系统错误。
|
||||
if err := writeBaseline(*baselineFlag, findings); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "commentlint: 写入基线失败:%v\n", err)
|
||||
if *modeFlag == "template-audit" {
|
||||
// templateFindings 保存按路径和行号排序的模板化注释位置。
|
||||
templateFindings, auditErr := collectTemplateCommentFindings(*rootFlag)
|
||||
if auditErr != nil {
|
||||
fmt.Fprintf(os.Stderr, "commentlint: %v\n", auditErr)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Printf("commentlint: 已记录 %d 个历史问题到 %s\n", len(findings), *baselineFlag)
|
||||
for _, finding /* finding 是当前需要输出给维护者的模板化注释记录。 */ := range templateFindings {
|
||||
fmt.Printf("%s:%d: [%s] 模板化注释\n", finding.File, finding.Line, finding.Kind)
|
||||
}
|
||||
fmt.Printf("commentlint: 发现 %d 条模板化注释\n", len(templateFindings))
|
||||
return
|
||||
}
|
||||
|
||||
// sortFindings 保证门禁输出在不同机器上保持稳定顺序。
|
||||
sortFindings(findings)
|
||||
if *modeFlag != "check" {
|
||||
fmt.Fprintf(os.Stderr, "commentlint: 不支持的模式 %q\n", *modeFlag)
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
// baseline 保存允许继续存在的历史问题,不允许新增问题混入主干。
|
||||
baseline, err := readBaseline(*baselineFlag)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "commentlint: 读取基线失败:%v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
// newFindings 只保留不在历史基线中的新增问题。
|
||||
newFindings := filterNewFindings(findings, baseline)
|
||||
// finding 表示当前待输出的一条新增注释问题。
|
||||
for _, finding := range newFindings {
|
||||
for _, finding := range findings {
|
||||
fmt.Printf("%s:%d: [%s] %s 缺少中文注释\n", finding.File, finding.Line, finding.Kind, finding.Name)
|
||||
}
|
||||
if len(newFindings) > 0 {
|
||||
fmt.Fprintf(os.Stderr, "commentlint: 发现 %d 个新增问题\n", len(newFindings))
|
||||
// templateFindings 是所有非冻结源码中仍需替换的机械注释。
|
||||
templateFindings, auditErr := collectTemplateCommentFindings(*rootFlag)
|
||||
if auditErr != nil {
|
||||
fmt.Fprintf(os.Stderr, "commentlint: %v\n", auditErr)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Printf("commentlint: 通过(扫描 %d 个历史问题)\n", len(findings))
|
||||
// finding 是当前需要输出给维护者的模板化注释记录。
|
||||
for _, finding := range templateFindings {
|
||||
fmt.Printf("%s:%d: [%s] 模板化注释\n", finding.File, finding.Line, finding.Kind)
|
||||
}
|
||||
if len(findings) > 0 || len(templateFindings) > 0 {
|
||||
fmt.Fprintf(os.Stderr, "commentlint: 发现 %d 个缺少中文注释项和 %d 条模板化注释\n", len(findings), len(templateFindings))
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Println("commentlint: 通过(无缺少中文注释或模板化注释)")
|
||||
}
|
||||
|
||||
// collectFindings 递归解析根目录下所有 Go 文件并收集缺少中文注释的声明。
|
||||
@@ -116,6 +136,79 @@ func collectFindings(root string) ([]Finding, error) {
|
||||
return findings, nil
|
||||
}
|
||||
|
||||
// collectTemplateCommentFindings 扫描 Go 源码中的模板化注释,供阶段 10 逐项替换为业务语义。
|
||||
func collectTemplateCommentFindings(root string) ([]Finding, error) {
|
||||
// findings 汇总所有模板化注释的位置与类别。
|
||||
findings := make([]Finding, 0)
|
||||
// walkErr 保存遍历源码树时遇到的文件系统错误。
|
||||
walkErr := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if info.IsDir() {
|
||||
if shouldSkipDirectory(path, root) {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, ".gen.go") {
|
||||
return nil
|
||||
}
|
||||
// relativePath 用于排除冻结 CAPTCHA 文件,避免审计器要求修改受保护实现。
|
||||
relativePath, relativeErr := filepath.Rel(root, path)
|
||||
if relativeErr != nil {
|
||||
return relativeErr
|
||||
}
|
||||
if isFrozenGoFile(filepath.ToSlash(relativePath)) {
|
||||
return nil
|
||||
}
|
||||
// fileFindings 是当前 Go 文件中命中的模板化注释。
|
||||
fileFindings, scanErr := templateFindingsInGoFile(root, path)
|
||||
if scanErr != nil {
|
||||
return scanErr
|
||||
}
|
||||
findings = append(findings, fileFindings...)
|
||||
return nil
|
||||
})
|
||||
if walkErr != nil {
|
||||
return nil, walkErr
|
||||
}
|
||||
sortFindings(findings)
|
||||
return findings, nil
|
||||
}
|
||||
|
||||
// templateFindingsInGoFile 只匹配单个 Go 文件的真实注释组,避免把字符串和测试夹具误判为注释。
|
||||
func templateFindingsInGoFile(root, path string) ([]Finding, error) {
|
||||
// fileSet 保存 AST 注释位置到源码行号的映射。
|
||||
fileSet := token.NewFileSet()
|
||||
// fileNode 是保留注释组的待审计 Go 语法树。
|
||||
fileNode, err := parser.ParseFile(fileSet, path, nil, parser.ParseComments)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析 %s 失败:%w", path, err)
|
||||
}
|
||||
// relativePath 是输出给维护者的仓库相对路径。
|
||||
relativePath, err := filepath.Rel(root, path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// findings 保存当前文件命中的模板化注释。
|
||||
findings := make([]Finding, 0)
|
||||
// commentGroup 是当前 AST 中可被业务代码实际读取到的注释组。
|
||||
for _, commentGroup := range fileNode.Comments {
|
||||
// commentText 是当前注释组的纯文本,排除了字符串字面量和测试夹具。
|
||||
commentText := commentGroup.Text()
|
||||
// line 是当前注释组在原文件中的首行,供维护者定位。
|
||||
line := fileSet.Position(commentGroup.Pos()).Line
|
||||
// pattern 是当前待匹配的历史模板规则。
|
||||
for _, pattern := range templateCommentPatterns {
|
||||
if pattern.expression.MatchString(commentText) {
|
||||
findings = append(findings, Finding{File: filepath.ToSlash(relativePath), Line: line, Kind: pattern.name, Name: "template-comment"})
|
||||
}
|
||||
}
|
||||
}
|
||||
return findings, nil
|
||||
}
|
||||
|
||||
// isFrozenGoFile 判断文件是否属于生产冻结的滑块/CAPTCHA 实现及测试。
|
||||
func isFrozenGoFile(relativePath string) bool {
|
||||
// frozenFiles 是与 AGENTS.md 及冻结规范一致的源码边界清单。
|
||||
@@ -338,66 +431,3 @@ func sortFindings(findings []Finding) {
|
||||
return findings[left].Name < findings[right].Name
|
||||
})
|
||||
}
|
||||
|
||||
// findingKey 生成基线记录的稳定键。
|
||||
func findingKey(finding Finding) string {
|
||||
return fmt.Sprintf("%s:%d:%s:%s", finding.File, finding.Line, finding.Kind, finding.Name)
|
||||
}
|
||||
|
||||
// writeBaseline 将当前发现写成可审查、可版本控制的 JSON 文件。
|
||||
func writeBaseline(path string, findings []Finding) error {
|
||||
// mkdirErr 表示创建基线目录时的文件系统错误。
|
||||
if mkdirErr := os.MkdirAll(filepath.Dir(path), 0o755); mkdirErr != nil {
|
||||
return mkdirErr
|
||||
}
|
||||
// file 是基线输出文件,使用缩进格式方便代码审查。
|
||||
file, err := os.Create(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
// encoder 负责以稳定缩进格式输出基线 JSON。
|
||||
encoder := json.NewEncoder(file)
|
||||
encoder.SetIndent("", " ")
|
||||
return encoder.Encode(findings)
|
||||
}
|
||||
|
||||
// readBaseline 读取历史基线并转换为快速查询集合。
|
||||
func readBaseline(path string) (map[string]struct{}, error) {
|
||||
// data 是基线文件的 JSON 内容。
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
// baselineMissing 表示严格门禁已删除历史基线文件,按空集合继续检查。
|
||||
if os.IsNotExist(err) {
|
||||
return map[string]struct{}{}, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
// findings 是反序列化后的历史问题列表。
|
||||
var findings []Finding
|
||||
// unmarshalErr 表示基线 JSON 无法解析的原因。
|
||||
if unmarshalErr := json.Unmarshal(data, &findings); unmarshalErr != nil {
|
||||
return nil, unmarshalErr
|
||||
}
|
||||
// baseline 是稳定键集合,避免检查阶段重复遍历历史列表。
|
||||
baseline := make(map[string]struct{}, len(findings))
|
||||
// finding 表示历史基线中的一条问题记录。
|
||||
for _, finding := range findings {
|
||||
baseline[findingKey(finding)] = struct{}{}
|
||||
}
|
||||
return baseline, nil
|
||||
}
|
||||
|
||||
// filterNewFindings 过滤掉已记录在历史基线中的问题。
|
||||
func filterNewFindings(findings []Finding, baseline map[string]struct{}) []Finding {
|
||||
// newFindings 保存真正需要开发者处理的新增问题。
|
||||
newFindings := make([]Finding, 0)
|
||||
// finding 表示本次扫描发现的一条问题记录。
|
||||
for _, finding := range findings {
|
||||
// exists 表示该问题是否已经被历史基线允许。
|
||||
if _, exists := baseline[findingKey(finding)]; !exists {
|
||||
newFindings = append(newFindings, finding)
|
||||
}
|
||||
}
|
||||
return newFindings
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestTemplateFindingsInGoFile 验证模板审计器会定位阶段 10 禁止的占位注释,并忽略正常业务说明。
|
||||
func TestTemplateFindingsInGoFile(t *testing.T) {
|
||||
// root 是承载独立 Go 源码夹具的临时目录。
|
||||
root := t.TempDir()
|
||||
// sourcePath 是写入模板与非模板注释混合夹具的路径。
|
||||
sourcePath := filepath.Join(root, "fixture.go")
|
||||
// source 是用于覆盖全部模板规则的最小 Go 源码文本。
|
||||
source := `package fixture
|
||||
// value 保存 value,供当前处理流程使用
|
||||
var value string
|
||||
// doWork 负责 doWork 相关处理。
|
||||
func doWork() {}
|
||||
// err 表示错误
|
||||
var err error
|
||||
// count 表示数量
|
||||
var count int
|
||||
// callback 回调函数负责当前业务流程。
|
||||
var callback = func() {}
|
||||
// accountID 是所有权校验通过后的非敏感账号标识。
|
||||
var accountID string
|
||||
`
|
||||
// err 是创建临时夹具时的文件系统错误。
|
||||
if err := os.WriteFile(sourcePath, []byte(source), 0o600); err != nil {
|
||||
t.Fatalf("写入模板注释夹具失败: %v", err)
|
||||
}
|
||||
// findings、err 是夹具扫描后的模板记录及文件读取错误。
|
||||
findings, err := templateFindingsInGoFile(root, sourcePath)
|
||||
if err != nil {
|
||||
t.Fatalf("templateFindingsInGoFile error: %v", err)
|
||||
}
|
||||
if len(findings) != 5 {
|
||||
t.Fatalf("模板记录数=%d,want 5: %+v", len(findings), findings)
|
||||
}
|
||||
// expectedKinds 是每种模板规则应至少命中一次的类别集合。
|
||||
expectedKinds := map[string]bool{
|
||||
"保存当前处理流程": false,
|
||||
"负责相关处理": false,
|
||||
"泛化错误说明": false,
|
||||
"泛化数量说明": false,
|
||||
"泛化回调职责": false,
|
||||
}
|
||||
// finding 是当前待核验的模板扫描记录。
|
||||
for _, finding := range findings {
|
||||
// exists 表示当前扫描记录是否属于本测试登记的模板类别。
|
||||
if _, exists := expectedKinds[finding.Kind]; !exists {
|
||||
t.Fatalf("出现未登记模板类别: %+v", finding)
|
||||
}
|
||||
expectedKinds[finding.Kind] = true
|
||||
}
|
||||
// kind、found 表示当前模板类别及其实际命中状态。
|
||||
for kind, found := range expectedKinds {
|
||||
if !found {
|
||||
t.Errorf("未命中模板类别 %q", kind)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,14 +8,14 @@ import (
|
||||
"os"
|
||||
)
|
||||
|
||||
// main 负责main相关处理。
|
||||
// main 封装main业务协调。
|
||||
func main() {
|
||||
if len(os.Args) != 3 {
|
||||
fmt.Fprintln(os.Stderr, "usage: iconconv input.png output.ico")
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
// data、err 保存data、err,供当前处理流程使用
|
||||
// data、err 用于本次流程后续判断的data、err
|
||||
data, err := os.ReadFile(os.Args[1])
|
||||
if err != nil {
|
||||
panic(err)
|
||||
@@ -23,16 +23,16 @@ func main() {
|
||||
|
||||
// A PNG-compressed 256x256 image is valid in an ICO file and keeps the
|
||||
// alpha channel of the original product icon.
|
||||
// headerSize 保存header数量,供当前处理流程使用
|
||||
// headerSize 用于本次流程后续判断的header数量
|
||||
const headerSize = 6
|
||||
// entrySize 保存entry数量,供当前处理流程使用
|
||||
// entrySize 用于本次流程后续判断的entry数量
|
||||
const entrySize = 16
|
||||
// result 保存结果,供当前处理流程使用
|
||||
// result 用于本次流程后续判断的结果
|
||||
result := make([]byte, headerSize+entrySize+len(data))
|
||||
binary.LittleEndian.PutUint16(result[0:2], 0)
|
||||
binary.LittleEndian.PutUint16(result[2:4], 1)
|
||||
binary.LittleEndian.PutUint16(result[4:6], 1)
|
||||
// entry 保存entry,供当前处理流程使用
|
||||
// entry 用于本次流程后续判断的entry
|
||||
entry := result[headerSize : headerSize+entrySize]
|
||||
entry[0] = 0 // 0 means 256 in the ICO format.
|
||||
entry[1] = 0
|
||||
@@ -42,7 +42,7 @@ func main() {
|
||||
binary.LittleEndian.PutUint32(entry[12:16], headerSize+entrySize)
|
||||
copy(result[headerSize+entrySize:], data)
|
||||
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := os.WriteFile(os.Args[2], result, 0644); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user