Skip to content

Commit

Permalink
feat: check func type
Browse files Browse the repository at this point in the history
  • Loading branch information
dengsgo committed Aug 27, 2023
1 parent 84be448 commit 67bd76d
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
11 changes: 9 additions & 2 deletions cmd/decorator/compile.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
)

const msgDecorPkgNotImported = "decorator used but package not imported (need add `import _ \"" + decoratorPackagePath + "\"`)"
const msgCantUsedOnDecoratorFunc = `decorators cannot be used on decorators`

func compile(args []string) error {
files := make([]string, 0, len(args))
Expand Down Expand Up @@ -113,13 +114,19 @@ func compile(args []string) error {
//x.Body.Rbrace = x.Body.Lbrace + token.Pos(ofs)
//log.Printf("fd.Body.Pos() %+v\n", fd.Body.Pos())
updated = true
name, ok := imp.importedPath(decoratorPackagePath)
pkgDecorName, ok := imp.importedPath(decoratorPackagePath)
if !ok {
logs.Error(msgDecorPkgNotImported, "\n\t",
friendlyIDEPosition(fset, doc.Pos()))
} else if name == "_" {
} else if pkgDecorName == "_" {
imp.pathObjMap[decoratorPackagePath].Name = nil // rewrite this package import way
imp.pathMap[decoratorPackagePath] = "decor" // mark finished
pkgDecorName = "decor"
}

if funIsDecorator(fd, pkgDecorName) {
logs.Error(msgCantUsedOnDecoratorFunc, "\n\t",
friendlyIDEPosition(fset, fd.Pos()))
}

if x := decorX(decorName); x != "" {
Expand Down
42 changes: 42 additions & 0 deletions cmd/decorator/lib_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package main

import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"testing"
)

Expand Down Expand Up @@ -86,3 +90,41 @@ b:=2`,
}
}
}

func TestFunIsDecorator(t *testing.T) {
check := func(name, pkgName string) {
code := testGetCode(name, pkgName)
f, err := parser.ParseFile(token.NewFileSet(), "main.go", code, parser.ParseComments)
if err != nil || f == nil || len(f.Decls) == 0 {
t.Fatal("TestFunIsDecorator testGetCode parse error", err)
}
i := 0
for _, v := range f.Decls {
fd, ok := v.(*ast.FuncDecl)
if !ok {
continue
}
i++
if funIsDecorator(fd, pkgName) && fd.Name.Name != "isDecorator" {
t.Fatal(fd.Name.Name, "should not be a decorator function")
}
}
if i == 0 {
t.Fatal("f.Decls have type *ast.FuncDecl functions. but got 0")
}
}
check("", "decor")
check("dec", "dec")
check("a", "a")
}

func testGetCode(name, pkgName string) string {
return fmt.Sprintf(`
package main
import %s "github.com/dengsgo/go-decorator/decor"
func isDecorator(ctx %s.Context) {}
func notDecorator1(ctx %s.Context, a int) {}
func notDecorator2(ctx %s.Contex) {}
func notDecorator3(a int) {}
`, name, pkgName, pkgName, pkgName)
}

0 comments on commit 67bd76d

Please sign in to comment.