github.com/unionj-cloud/go-doudou/v2@v2.3.5/toolkit/astutils/helper.go (about)

     1  package astutils
     2  
     3  import (
     4  	"github.com/pkg/errors"
     5  	"go/ast"
     6  	"go/parser"
     7  	"go/token"
     8  	"golang.org/x/tools/go/packages"
     9  	"path/filepath"
    10  	"strings"
    11  )
    12  
    13  func IsSlice(t string) bool {
    14  	return strings.Contains(t, "[") || strings.HasPrefix(t, "...")
    15  }
    16  
    17  func IsVarargs(t string) bool {
    18  	return strings.HasPrefix(t, "...")
    19  }
    20  
    21  func ToSlice(t string) string {
    22  	return "[]" + strings.TrimPrefix(t, "...")
    23  }
    24  
    25  // ElementType get element type string from slice
    26  func ElementType(t string) string {
    27  	if IsVarargs(t) {
    28  		return strings.TrimPrefix(t, "...")
    29  	}
    30  	return t[strings.Index(t, "]")+1:]
    31  }
    32  
    33  func CollectStructsInFolder(dir string, sc *StructCollector) {
    34  	dir, _ = filepath.Abs(dir)
    35  	var files []string
    36  	err := filepath.Walk(dir, Visit(&files))
    37  	if err != nil {
    38  		panic(err)
    39  	}
    40  	for _, file := range files {
    41  		if filepath.Ext(file) != ".go" {
    42  			continue
    43  		}
    44  		root, err := parser.ParseFile(token.NewFileSet(), file, nil, parser.ParseComments)
    45  		if err != nil {
    46  			panic(err)
    47  		}
    48  		ast.Walk(sc, root)
    49  	}
    50  }
    51  
    52  func GetPkgPath(filePath string) string {
    53  	pkgs, err := packages.Load(&packages.Config{
    54  		Mode: packages.NeedName,
    55  		Dir:  filePath,
    56  	})
    57  	if err != nil {
    58  		panic(err)
    59  	}
    60  	if len(pkgs) == 0 {
    61  		panic(errors.New("no package found"))
    62  	}
    63  	if len(pkgs[0].Errors) > 0 {
    64  		for _, err = range pkgs[0].Errors {
    65  			panic(err)
    66  		}
    67  	}
    68  	return pkgs[0].PkgPath
    69  }