Skip to content

Commit

Permalink
coveralls
Browse files Browse the repository at this point in the history
  • Loading branch information
celt237 committed Jul 1, 2024
1 parent 5c1b81f commit da94ff1
Show file tree
Hide file tree
Showing 10 changed files with 165 additions and 101 deletions.
7 changes: 7 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,10 @@ install:

.PHONY:
help deps gen check test citest coverage install all

#release:
# @echo "---------------------"
# @echo "Building release binary"
# @echo "---------------------"
# mkdir -p release
# CGO_ENABLED=0 GOOS=linux go build -a -ldflags '-s -w' -o release/
27 changes: 27 additions & 0 deletions go-annotation.go
Original file line number Diff line number Diff line change
@@ -1 +1,28 @@
package go_annotation

import "github.com/celt237/go-annotation/internal"

// GetFileDesc 获取文件描述
// fileName: 文件名
func GetFileDesc(fileName string) (*internal.FileDesc, error) {
return internal.GetFileParser(fileName).Parse()
}

// GetFilesDescList 获取文件描述列表
// directory: 目录
func GetFilesDescList(directory string) ([]*internal.FileDesc, error) {
var filesDesc []*internal.FileDesc
// 读取目录下的所有文件
fileNames, err := internal.GetFileNames(directory)
if err != nil {
return nil, err
}
for _, fileName := range fileNames {
fileDesc, err := GetFileDesc(fileName)
if err != nil {
return nil, err
}
filesDesc = append(filesDesc, fileDesc)
}
return filesDesc, nil
}
92 changes: 92 additions & 0 deletions internal/annotationParser.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package internal

import (
"strconv"
"strings"
)

type AnnotationParser interface {
Parse(comments []string) map[string]*Annotation
}

func getAnnotationParser(mode AnnotationMode) AnnotationParser {
switch mode {
case AnnotationModeMap:
return &MapAnnotationParser{}
default:
return &ArrayAnnotationParser{}
}
}

type ArrayAnnotationParser struct{}

func (a *ArrayAnnotationParser) Parse(comments []string) map[string]*Annotation {
annotations := make(map[string]*Annotation)
for _, comment := range comments {
commentSlice := splitComment(comment)
if len(commentSlice) == 0 {
continue
}
name := commentSlice[0]
attribute := make(map[string]string)
for i := 1; i < len(commentSlice); i++ {
attribute[strconv.Itoa(i-1)] = commentSlice[i]
}
if _, ok := annotations[name]; ok {
if len(attribute) > 0 {
annotations[name].Attributes = append(annotations[name].Attributes, attribute)
}
} else {
annotation := &Annotation{Name: name, Attributes: []map[string]string{}}
if len(attribute) > 0 {
annotation.Attributes = append(annotation.Attributes, attribute)
}
annotations[name] = annotation
}
}
return annotations
}

type MapAnnotationParser struct{}

func (a *MapAnnotationParser) Parse(comments []string) map[string]*Annotation {
annotations := make(map[string]*Annotation)
for _, comment := range comments {
if strings.Contains(comment, "(") {
// get annotation name
name := comment[:strings.Index(comment, "(")]
// get attribute
attributeStr := comment[strings.Index(comment, "(")+1 : strings.LastIndex(comment, ")")]
attributeSlice := strings.Split(attributeStr, ",")
attribute := make(map[string]string)
for _, item := range attributeSlice {
// get attribute name and value
itemSlice := strings.Split(item, "=")
if len(itemSlice) != 2 {
continue
}
attributeName := strings.TrimSpace(itemSlice[0])
attributeValue := strings.TrimSpace(itemSlice[1])
if strings.HasPrefix(attributeValue, "\"") && strings.HasSuffix(attributeValue, "\"") {
attributeValue = attributeValue[1 : len(attributeValue)-1]
}
attribute[attributeName] = attributeValue
}
if _, ok := annotations[name]; ok {
if len(attribute) > 0 {
annotations[name].Attributes = append(annotations[name].Attributes, attribute)
}
} else {
annotation := &Annotation{Name: name, Attributes: []map[string]string{}}
if len(attribute) > 0 {
annotation.Attributes = append(annotation.Attributes, attribute)
}
annotations[name] = annotation
}
} else {
annotation := &Annotation{Name: comment, Attributes: []map[string]string{}}
annotations[comment] = annotation
}
}
return annotations
}
14 changes: 7 additions & 7 deletions internal/annotation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"testing"
)

func get_arraymode_single_interface(fileName string) *FileDesc {
func getInstanceFromJsonFile(fileName string) *FileDesc {
jsonFile, err := os.Open(fileName)
if err != nil {
fmt.Println(err)
Expand Down Expand Up @@ -37,42 +37,42 @@ func TestAnnotation(t *testing.T) {
name: "数组模式单接口测试",
fileName: "test/data/arraymode/arraymode_single_interface.go",
mode: AnnotationModeArray,
wantResult: get_arraymode_single_interface("test/data/arraymode/arraymode_single_interface.json"),
wantResult: getInstanceFromJsonFile("test/data/arraymode/arraymode_single_interface.json"),
wantErr: false,
},
{
name: "数组模式单结构体测试",
fileName: "test/data/arraymode/arraymode_single_struct.go",
mode: AnnotationModeArray,
wantResult: get_arraymode_single_interface("test/data/arraymode/arraymode_single_struct.json"),
wantResult: getInstanceFromJsonFile("test/data/arraymode/arraymode_single_struct.json"),
wantErr: false,
},
{
name: "数组模式混合测试",
fileName: "test/data/arraymode/arraymode_mult.go",
mode: AnnotationModeArray,
wantResult: get_arraymode_single_interface("test/data/arraymode/arraymode_mult.json"),
wantResult: getInstanceFromJsonFile("test/data/arraymode/arraymode_mult.json"),
wantErr: false,
},
{
name: "map模式单接口测试",
fileName: "test/data/mapmode/mapmode_single_interface.go",
mode: AnnotationModeMap,
wantResult: get_arraymode_single_interface("test/data/mapmode/mapmode_single_interface.json"),
wantResult: getInstanceFromJsonFile("test/data/mapmode/mapmode_single_interface.json"),
wantErr: false,
},
{
name: "map模式单结构体测试",
fileName: "test/data/mapmode/mapmode_single_struct.go",
mode: AnnotationModeMap,
wantResult: get_arraymode_single_interface("test/data/mapmode/mapmode_single_struct.json"),
wantResult: getInstanceFromJsonFile("test/data/mapmode/mapmode_single_struct.json"),
wantErr: false,
},
{
name: "map模式混合测试",
fileName: "test/data/mapmode/mapmode_mult.go",
mode: AnnotationModeMap,
wantResult: get_arraymode_single_interface("test/data/mapmode/mapmode_mult.json"),
wantResult: getInstanceFromJsonFile("test/data/mapmode/mapmode_mult.json"),
wantErr: false,
},
}
Expand Down
84 changes: 4 additions & 80 deletions internal/astParser.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
)

Expand Down Expand Up @@ -51,7 +50,7 @@ func getFullPackageName(moduleName string, filePath string) string {
dirPath := filepath.Dir(relativePath)
importPath := filepath.ToSlash(dirPath)

fullPackageName := moduleName + "/" + importPath // 模块名 + 相对路径
fullPackageName := moduleName + "/" + importPath
return fullPackageName
}

Expand All @@ -77,7 +76,7 @@ func parseDescription(name string, commentGroup *ast.CommentGroup) (description
prefix := "// " + name
for _, com := range commentGroup.List {
if strings.HasPrefix(com.Text, prefix) {
// 取前缀之后的内容 去掉前后空格
// Remove the prefix and trim the spaces
description = strings.TrimSpace(strings.TrimPrefix(com.Text, prefix))
break
}
Expand All @@ -86,77 +85,8 @@ func parseDescription(name string, commentGroup *ast.CommentGroup) (description

}

func parseAnnotation(comments []string, mode AnnotationMode) (annotations map[string]*Annotation) {
annotations = make(map[string]*Annotation)
for _, comment := range comments {
if mode == AnnotationModeArray {
commentSlice := splitComment(comment)
if len(commentSlice) == 0 {
continue
}
name := commentSlice[0]
attribute := make(map[string]string)
for i := 1; i < len(commentSlice); i++ {
attribute[strconv.Itoa(i-1)] = commentSlice[i]
}
if _, ok := annotations[name]; ok {
if len(attribute) > 0 {
annotations[name].Attributes = append(annotations[name].Attributes, attribute)
}
} else {
annotation := &Annotation{Name: name, Attributes: []map[string]string{}}
if len(attribute) > 0 {
annotation.Attributes = append(annotation.Attributes, attribute)
}
annotations[name] = annotation
}
} else {
// map mode
if strings.Contains(comment, "(") {
// 获取注解名
name := comment[:strings.Index(comment, "(")]
// 获取注解属性
attributeStr := comment[strings.Index(comment, "(")+1 : strings.LastIndex(comment, ")")]
attributeSlice := strings.Split(attributeStr, ",")
attribute := make(map[string]string)
for _, item := range attributeSlice {
// 获取属性名和属性值
itemSlice := strings.Split(item, "=")
if len(itemSlice) != 2 {
continue
}
attributeName := strings.TrimSpace(itemSlice[0])
attributeValue := strings.TrimSpace(itemSlice[1])
// attributeValue去掉引号
if strings.HasPrefix(attributeValue, "\"") && strings.HasSuffix(attributeValue, "\"") {
attributeValue = attributeValue[1 : len(attributeValue)-1]
}
attribute[attributeName] = attributeValue
}
if _, ok := annotations[name]; ok {
if len(attribute) > 0 {
annotations[name].Attributes = append(annotations[name].Attributes, attribute)
}
} else {
annotation := &Annotation{Name: name, Attributes: []map[string]string{}}
if len(attribute) > 0 {
annotation.Attributes = append(annotation.Attributes, attribute)
}
annotations[name] = annotation
}
} else {
// 不包含"("的注解
annotation := &Annotation{Name: comment, Attributes: []map[string]string{}}
annotations[comment] = annotation
}

}
}
return annotations
}

func splitComment(comment string) []string {
re := regexp.MustCompile("[\\s ]") // 使用半角空格和全角空格作为分隔符
re := regexp.MustCompile("[\\s ]") // Use half-width space and full-width space as separators
commentSlice := re.Split(comment, -1)
var filteredSlice []string
for _, item := range commentSlice {
Expand Down Expand Up @@ -204,22 +134,17 @@ func exprToString(expr ast.Expr) string {

switch t := expr.(type) {
case *ast.Ident:
// 标识符
return t.Name
case *ast.SelectorExpr:
// 选择器
return exprToString(t.X) + "." + t.Sel.Name
case *ast.StarExpr:
// 指针类型
// pointer
return "*" + exprToString(t.X)
case *ast.ArrayType:
// 数组或切片类型
return "[]" + exprToString(t.Elt)
case *ast.MapType:
// map类型
return "map[" + exprToString(t.Key) + "]" + exprToString(t.Value)
case *ast.StructType:
// 结构体类型
var fields []string
for _, field := range t.Fields.List {
var names []string
Expand All @@ -230,7 +155,6 @@ func exprToString(expr ast.Expr) string {
}
return "struct{" + strings.Join(fields, "; ") + "}"
case *ast.InterfaceType:
// 接口类型
if t.Methods == nil || len(t.Methods.List) == 0 {
return "interface{}"
}
Expand Down
4 changes: 0 additions & 4 deletions internal/config.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
package internal

var GenFilePrefix = "gen_"

var ProjectPath = "internal/test/data"

const AnnotationPrefix = "@"

var CurrentAnnotationMode = AnnotationModeArray
12 changes: 12 additions & 0 deletions internal/fileParser.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"go/parser"
"go/token"
"os"
"path/filepath"
"strings"
)

Expand All @@ -17,6 +18,17 @@ func GetFileParser(filePath string) *FileParser {
return &FileParser{filePath: filePath}
}

func GetFileNames(directory string) ([]string, error) {
fileNames := make([]string, 0)
err := filepath.Walk(directory, func(path string, info os.FileInfo, err error) error {
if !info.IsDir() && strings.HasSuffix(info.Name(), ".go") {
fileNames = append(fileNames, path)
}
return nil
})
return fileNames, err
}

func (f *FileParser) Parse() (*FileDesc, error) {
// parse file
fset := token.NewFileSet()
Expand Down
12 changes: 12 additions & 0 deletions internal/generate/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package generate

type Config struct {
// service文件所在目录 必传
SourcePath string `yaml:"servicePath"`

// 要生成的代码文件所在目录 必传
GenFilePath string `yaml:"genFilePath"`

// 模版文件地址
TemplateFile string `yaml:"templateFile"`
}
4 changes: 2 additions & 2 deletions internal/interfaceParser.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func (s *InterfaceParser) Parse() (*InterfaceDesc, error) {
Methods: methods,
Imports: s.parserImports(methods),
Comments: comments,
Annotations: parseAnnotation(comments, CurrentAnnotationMode),
Annotations: getAnnotationParser(CurrentAnnotationMode).Parse(comments),
}
return sDesc, nil
}
Expand Down Expand Up @@ -105,7 +105,7 @@ func (s *InterfaceParser) parserMethod(method *ast.Field) (methodDesc *MethodDes
// comment
methodDesc.Comments = parseAtComments(method.Doc)
methodDesc.Description = parseDescription(methodDesc.Name, method.Doc)
methodDesc.Annotations = parseAnnotation(methodDesc.Comments, CurrentAnnotationMode)
methodDesc.Annotations = getAnnotationParser(CurrentAnnotationMode).Parse(methodDesc.Comments)
return methodDesc, err
} else {
err = fmt.Errorf("method type is not funcType")
Expand Down
Loading

0 comments on commit da94ff1

Please sign in to comment.