package models import ( "go/ast" "go/parser" "go/token" "os" "regexp" "testing" ) var chineseText = regexp.MustCompile(`[\p{Han}]`) func TestEveryModelFieldHasChineseComment(t *testing.T) { packages, err := parser.ParseDir(token.NewFileSet(), ".", func(info os.FileInfo) bool { return info.Name() != "comments_test.go" }, parser.ParseComments) if err != nil { t.Fatal(err) } for _, file := range packages["models"].Files { ast.Inspect(file, func(node ast.Node) bool { typeSpec, ok := node.(*ast.TypeSpec) if !ok { return true } structType, ok := typeSpec.Type.(*ast.StructType) if !ok { return false } for _, field := range structType.Fields.List { name := "embedded field" if len(field.Names) > 0 { name = field.Names[0].Name if !ast.IsExported(name) { continue } } comment := "" if field.Doc != nil { comment += field.Doc.Text() } if field.Comment != nil { comment += field.Comment.Text() } if !chineseText.MatchString(comment) { t.Errorf("%s.%s 缺少中文字段注释", typeSpec.Name.Name, name) } } return false }) } }